minify

@param string $file
@param string $type

@return  static
193168
public function minify($file, $type = null)
    {
        if ($type === null) {
            $type = File::getExtension($file);
        }

        $type = strtolower($type);

        if ($type === 'css') {
            $content = CssMinifier::process(file_get_contents($file));
        } elseif ($type === 'js') {
            $content = JsMinifier::process(file_get_contents($file));
        } else {
            return $this;
        }

        $dest = dirname($file) . '/' . File::stripExtension(File::getFilename($file)) . '.min.' . $type;

        file_put_contents($dest, $content);

        $this->out('Minify file: ' . $dest);

        return $this;
    }
359336
public static function forge($file = null, $data = null, $auto_filter = null)
	{
		return new static($file, $data, $auto_filter);
	}
371225
public function change_perm_by_real($file, $file_new, $type='file'){
    if ( !empty($file) &&
      !empty($file_new) &&
      file_exists($file_new) &&
      ($id_opt = $this->real_to_perm($file, $type)) &&
      !$this->real_to_perm($file_new, $type)
    ){
      $is_file = $type === 'file';
      $code = $is_file ? bbn\str::file_ext(basename($file_new), 1)[0] : basename($file_new).'/';
      if ( ($id_parent = $this->create_perm_by_real(dirname($file_new).'/', 'dir'))
      ){
        $this->options->set_prop($id_opt, ['code' => $code]);
        $this->options->move($id_opt, $id_parent);
        return true;
      }
    }
    return false;
  }
821161
function mediaType( $file ) {

		$mime = static::mimeType( $file );
		$mime = explode( ';', $mime );
		$mime = trim( $mime[0] );

		return $mime;
	}
1215418
public function setFile($file)
    {
        $path = pathinfo((string) $file);

        if (!$path['extension'])
            $file .= '.'.static::$_defaultExt;

        $this->_file = trim($file, DIRECTORY_SEPARATOR);

        return $this;
    }
924438
public function attach($file, $name = null, $type = null)
    {
        if (!$file instanceof MailAttachment) {
            $file = new MailAttachment($file);
        }

        if ($name) {
            $file->setFilename($name);
        }

        if ($type) {
            $file->setContentType($type);
        }

        $this->files[] = $file;

        return $this;
    }
636418
public function setFile(\Sulu\Bundle\MediaBundle\Entity\File $file = null)
    {
        $this->file = $file;

        return $this;
    }
1121454
public function minify($collection) {
		// check final path
		$public_path = $this->f3->get('ASSETS.minify.public_path');
		if (!is_dir($public_path))
			mkdir($public_path,0777,true);
		$type = false;
		$inline_stack = array();
		foreach($collection as $i=>&$asset) {
			$type = $asset['type'];
			if ($asset['origin']=='inline') {
				$slot = $asset['slot'] ?: 'default';
				$inline_stack[$slot][] = $asset['data'];
				unset($collection[$i]);
				unset($asset);
				continue;
			}
			$path = $asset['path'];
			$exclude = $this->f3->get('ASSETS.minify.exclude');
			// skip external files
			if ($asset['origin'] == 'external')
				continue;
			elseif (is_file($path) && (
				(!isset($asset['exclude']) ||
					!in_array('minify',$this->f3->split($asset['exclude']))) &&
				(empty($exclude) || !preg_match('/'.$exclude.'/i',$path)))) {
				// proceed
				$path_parts = pathinfo($path);
				$filename = $path_parts['filename'].'.'
					.substr($this->f3->hash($path),0,5).'.min.'.$type;
				if (!is_file($public_path.$filename) ||
					(filemtime($path)>filemtime($public_path.$filename))) {
					$min = $this->f3->call($this->f3->get('ASSETS.minify.compiler.'.$type),
						[$path_parts['basename'],$path_parts['dirname'].'/']);
					if ($type=='css')
						$min = $this->fixRelativePaths($min,
							$path_parts['dirname'].'/',$public_path);
					$this->f3->write($public_path.$filename,$min);
				}
				$asset['path'] = $public_path.$filename;
			}
			unset($asset);
		}
		if (!empty($inline_stack)) {
			foreach ($inline_stack as $slotGroup=>$inlineData) {
				$data = implode($inlineData);
				if ($this->f3->get('ASSETS.minify.inline')) {
					// this is probably pretty slow
					$hash = $this->f3->hash($data);
					$filename = $hash.'.min.'.$type;
					if (!is_file($public_path.$filename)) {
						$this->f3->write($public_path.$filename,$data);
						$min = \Web::instance()->minify($filename,null,false,
							$public_path);
						$this->f3->write($public_path.$filename,$min);
					}
					$collection[] = array(
						'path'=>$public_path.$filename,
						'type'=>$type,
						'origin'=>'internal',
						'slot'=>$slotGroup,
					);
				} else {
					$collection[] = array(
						'data'=>$data,
						'type'=>$type,
						'origin'=>'inline',
						'slot'=>$slotGroup,
					);
				}
			}
		}
		return $collection;
	}
1045181
protected function minifyContent($type, $content)
    {
        $minifier = null;
        if ($type === AssetManager::CSS) {
            $minifier = new \MatthiasMullie\Minify\CSS($content);
        } else if ($type === AssetManager::JS) {
            $minifier = new \MatthiasMullie\Minify\JS($content);
        }
        
        if ($minifier !== null) {
            return $minifier->minify();
        }
        
        return $content;
    }
729632
protected function buildTypeCache($type, $files)
    {
        $typeContent = '';
        $fileHashs = array();

        // Generate the content for all the files
        foreach ($files as $file) {
            $fileName = $file->getFileName();
            if (!file_exists($fileName)) {
                continue;
            }

            // Load the content
            $content = $this->fileBackend->loadFromFile($fileName);
            
            // Optimze the content
            $content = $this->optimizeContent($type, $fileName, $content);
            
            // Add the content and save the file hash
            $typeContent .= $content;
            $fileHashs[$this->getHash($fileName)] = md5_file($fileName);
        }

        // Minify the content, if possible and activated
        if (($type === AssetManager::CSS || $type === AssetManager::JS) && $this->minifyAssets) {
            $typeContent = $this->minifyContent($type, $typeContent);
        }
        
        // Generate the hash and the new file name
        $hash = $this->getTypeHash($type);
        $version = $type . '-' . uniqid() . '.' . $this->getExtensionForType($type);
        $targetFile = $this->buildFilePath($type, $hash, $version);

        // Save the cached file
        $this->removeOldTypeCacheFile($type);
        $this->fileBackend->saveToFile($typeContent, $targetFile);

        // Save the cached files in the data array
        $this->cachedFiles[$hash] = array(
            'file' => $targetFile, 
            'checksums' => $fileHashs,
            'timestamp' => time()
        );
        $this->saveAssetsCache();
        
        return $targetFile;
    }
909171
public function uploadFrom($file, $type = 'image')
    {
        if (!$file || !$type) {
            $this->setError('参数缺失');

            return false;
        }

        $this->setPostQueryStr('type', $type);

        $name        = 'media'; // 设置上传文件键名 固定为media
        $filename    = $file['name']; // 设置上传文件名
        $filetype    = $file['type'];
        $filecontent = file_get_contents($file['tmp_name']); // 读取临时文件里 上传文件的信息
        $key         = "name=\"{$name}\"; filename=\"{$filename}\"\r\nContent-Type: {$filetype}\r\n"; // curl设置上传文件的一种方法.

        $param       = [];
        $param[$key] = $filecontent;

        $node = 'upload';

        $res = $this->_post($node, $param, false);

        return $res;
    }
599856
function minify($files,$mime=NULL,$header=TRUE,$path=NULL) {
		$fw=Base::instance();
		if (is_string($files))
			$files=$fw->split($files);
		if (!$mime)
			$mime=$this->mime($files[0]);
		preg_match('/\w+$/',$files[0],$ext);
		$cache=Cache::instance();
		$dst='';
		if (!isset($path))
			$path=$fw->UI.';./';
		foreach ($fw->split($path,FALSE) as $dir)
			foreach ($files as $file)
				if (is_file($save=$fw->fixslashes($dir.$file)) &&
					is_bool(strpos($save,'../')) &&
					preg_match('/\.(css|js)$/i',$file)) {
					if ($fw->CACHE &&
						($cached=$cache->exists(
							$hash=$fw->hash($save).'.'.$ext[0],$data)) &&
						$cached[0]>filemtime($save))
						$dst.=$data;
					else {
						$data='';
						$src=$fw->read($save);
						for ($ptr=0,$len=strlen($src);$ptr<$len;) {
							if (preg_match('/^@import\h+url'.
								'\(\h*([\'"])((?!(?:https?:)?\/\/).+?)\1\h*\)[^;]*;/',
								substr($src,$ptr),$parts)) {
								$path=dirname($file);
								$data.=$this->minify(
									($path?($path.'/'):'').$parts[2],
									$mime,$header
								);
								$ptr+=strlen($parts[0]);
								continue;
							}
							if ($ext[0]=='css'&&preg_match('/^url\(([^\'"].*?[^\'"])\)/i',
									substr($src,$ptr),$parts)) {
								$data.=$parts[0];
								$ptr+=strlen($parts[0]);
								continue;
							}
							if ($src[$ptr]=='/') {
								if ($src[$ptr+1]=='*') {
									// Multiline comment
									$str=strstr(
										substr($src,$ptr+2),'*/',TRUE);
									$ptr+=strlen($str)+4;
								}
								elseif ($src[$ptr+1]=='/') {
									// Single-line comment
									$str=strstr(
										substr($src,$ptr+2),"\n",TRUE);
									$ptr+=(empty($str))?
										strlen(substr($src,$ptr)):strlen($str)+2;
								}
								else {
									// Presume it's a regex pattern
									$regex=TRUE;
									// Backtrack and validate
									for ($ofs=$ptr;$ofs;$ofs--) {
										// Pattern should be preceded by
										// open parenthesis, colon,
										// object property or operator
										if (preg_match(
											'/(return|[(:=!+\-*&|])$/',
											substr($src,0,$ofs))) {
											$data.='/';
											$ptr++;
											while ($ptr<$len) {
												$data.=$src[$ptr];
												$ptr++;
												if ($src[$ptr-1]=='\\') {
													$data.=$src[$ptr];
													$ptr++;
												}
												elseif ($src[$ptr-1]=='/')
													break;
											}
											break;
										}
										elseif (!ctype_space($src[$ofs-1])) {
											// Not a regex pattern
											$regex=FALSE;
											break;
										}
									}
									if (!$regex) {
										// Division operator
										$data.=$src[$ptr];
										$ptr++;
									}
								}
								continue;
							}
							if (in_array($src[$ptr],['\'','"'])) {
								$match=$src[$ptr];
								$data.=$match;
								$ptr++;
								// String literal
								while ($ptr<$len) {
									$data.=$src[$ptr];
									$ptr++;
									if ($src[$ptr-1]=='\\') {
										$data.=$src[$ptr];
										$ptr++;
									}
									elseif ($src[$ptr-1]==$match)
										break;
								}
								continue;
							}
							if (ctype_space($src[$ptr])) {
								if ($ptr+1<strlen($src) &&
									preg_match('/[\w'.($ext[0]=='css'?
										'#\.%+\-*()\[\]':'\$').']{2}|'.
										'[+\-]{2}/',
										substr($data,-1).$src[$ptr+1]) ||
									($ext[0]=='css' && $ptr+2<strlen($src) &&
									preg_match('/:\w/',substr($src,$ptr+1,2))))
									$data.=' ';
								$ptr++;
								continue;
							}
							$data.=$src[$ptr];
							$ptr++;
						}
						if ($ext[0]=='css')
							$data=str_replace(';}','}',$data);
						if ($fw->CACHE)
							$cache->set($hash,$data);
						$dst.=$data;
					}
				}
		if (PHP_SAPI!='cli' && $header)
			header('Content-Type: '.$mime.'; charset='.$fw->ENCODING);
		return $dst;
	}
849713
public function minify()
    {
        $cleaned_stack = $this->cleanStack($this->get(), 'path');
        if (!empty($cleaned_stack)) {
            foreach ($cleaned_stack as $i=>$item) {
                if (isset($item['minified']) && true===$item['minified']) {
                    unset($cleaned_stack[$i]);
                }
            }
        }
        if (!empty($cleaned_stack)) {
            $this->addMinified(
                $this->minifyStack($this->extractFromStack($cleaned_stack, 'path'))
            );
        }
        return $this;
    }
985975
public function file($file, $type, $filename = null)
    {
        $this->type = $type;

        if(is_file($file))
        {
            $this->payload['file'] = ['name' => $type, 'contents'=> fopen($file, 'r')];
            if($filename)
                $this->payload['file']['filename'] = $filename;
        }
        else
            $this->payload[$type] = $file;

        return $this;
    }
1204442
final protected function createImageFromFile($file, $type)
    {
        switch ($type) {
            case \IMAGETYPE_GIF:
                return imagecreatefromgif($file);

            case \IMAGETYPE_JPEG:
                return imagecreatefromjpeg($file);

            case \IMAGETYPE_PNG:
                return imagecreatefrompng($file);
    
            default:
                throw new LogicException(sprintf('Can not create image from "%s"', $file));
        }
    }
844619
public function minify($src)
	{
		$options = ($this->options) ? ' ' . $this->options : '';

		// Add our custom externs if default externs are disabled
		if ($this->excludeDefaultExterns && $this->compilationLevel === 'ADVANCED_OPTIMIZATIONS')
		{
			$options .= ' --externs ' . __DIR__ . '/../externs.application.js --env=CUSTOM';
		}

		$crc     = crc32($src);
		$inFile  = sys_get_temp_dir() . '/' . $crc . '.js';
		$outFile = sys_get_temp_dir() . '/' . $crc . '.min.js';
		file_put_contents($inFile, $src);

		$cmd = $this->command
		     . ' --compilation_level ' . escapeshellarg($this->compilationLevel)
		     . $options
		     . ' --js ' . escapeshellarg($inFile)
		     . ' --js_output_file ' . escapeshellarg($outFile);

		exec($cmd . ' 2>&1', $output, $return);
		unlink($inFile);

		if (file_exists($outFile))
		{
			$src = trim(file_get_contents($outFile));
			unlink($outFile);
		}

		if (!empty($return))
		{
			throw new RuntimeException('An error occured during minification: ' . implode("\n", $output));
		}

		return $src;
	}
90452
public function cssMinify($file, $type = 'file')
    {
        $file = $this->getFile($file, $type);
        $file = $this->cleanSpaces($file);
        $file = $this->fixMaster($file);
        $file = $this->removeComments($file);

        return preg_replace(['/;[\s\r\n\t]*?}[\s\r\n\t]*/ims', '/;[\s\r\n\t]/ims', '/[\s\r\n\t]*:[\s\r\n\t][\s+\/]/ims', '/[\s\r\n\t]*,[\s\r\n\t]*?([^\s\r\n\t]\.[\s+\/])/ims', '/[\s\r\n\t]/ims', '/([\d\.]+)[\s\r\n\t]+(px|em|pt|%)/ims', '/([^\s\.]0)(px|em|pt|%|ex|mm|in|pc|vh|vw|vmin)/ims', '/\s+/'], ['}', ';$1', ',$1', '$1', '$1$2', '$1$2', ' '], $file);
    }