<?php /** * @author:jiangzaixing 20160314 * 获取静态文件方法 */ class StaticFile { const MAP_FILE_NAME = 'map.json'; static public $files = null; static public $fileMap = null; //静态文件地址对应map //要操作的目录 static public $pathList = array( 'image/', 'css/', 'js/' ); //需要压缩的文件 static public $extList = array( 'js','css','gif','jpg','png' ); static public $toPath = 'scripts/temp/'; /** * 获取最新的静态文件 * @param string $fName 文件名称 */ static public function getFile( $fName ){ $from = dirname(__FILE__).'/../../scripts/' ; $to = dirname(__FILE__).'/../../scripts/temp/'; if( !self::$fileMap ) self::$fileMap = json_decode( file_get_contents( $to.self::MAP_FILE_NAME ) ,true ); return self::$fileMap[md5($fName)]; } /** * 批量生成新的静态文件 */ static public function genFiles(){ $from = dirname(__FILE__).'/../../scripts/' ; $to = dirname(__FILE__).'/../../scripts/temp/' ; foreach( self::$pathList as $path ){ self::scanfDir( $from.$path ); } foreach ( self::$files as $file ){ self::genFile( $file , $from , $to); } $sMap = file_put_contents( $to.self::MAP_FILE_NAME, json_encode( self::$fileMap ) ); } static public function scanfDir( $dir , $level = 0 ){ if(( $level == 0 &&!is_dir($dir)) || !is_readable($dir)){ return array( 'isOk'=>false , 'msg'=>"$dir 路径无效" ); } $handler = opendir($dir); while( false !== ($file = readdir($handler)) ){ if(in_array($file,array('.','..'))) continue; if(is_dir( $dir.$file )){ self::scanfDir( $dir.$file."/", $lev = $level+1 ); continue; } self::$files[] = $dir.$file; } closedir($handler); } /** * 创建多级目录 */ static public function createDir( $path ){ if (file_exists($path)) return true; self::createDir(dirname($path)); mkdir($path, 0777); } /** * 替换css中图片地址 只能写死了。 */ static public function replaceCssImg( $content , $from , $to ){ $ret = preg_replace_callback('/url(/scripts/([sS]*?))/',function( $m ){ $_idx = md5( $m[1] ); return '/scripts/temp/'.self::$fileMap[$_idx]; }, $content); unset( $content ); return $ret; } /** * 生成对应文件 */ static public function genFile( $file, $from ,$to ){ $len = strlen( $from ); //获取文件在目录中的目录结构 创建文件夹 $info = pathinfo($file); $relUrl = substr( $file, $len ); $_path = dirname( $relUrl ); self::createDir( $to.$_path ); //获取静态文件内容 $_fcontent = file_get_contents($file); if( $info['extension'] == 'css' ) $_fcontent = self::replaceCssImg( $_fcontent , $from , $to ); if( in_array( $info['extension'] , self::$extList ) ){ //生成静态文件MD5值 $_idx = md5_file( $file ); $newName = sprintf( '%s.%s.%s', $info['filename'], $_idx, $info['extension']); file_put_contents( $to.$_path.'/'.$newName, $_fcontent); self::$fileMap[md5($relUrl)] = $_path.'/'.$newName; } // 保存文件内容到新文件 $_oname = sprintf( '%s/%s.%s', $to.$_path, $info['filename'], $info['extension'] ); $ret = file_put_contents( $_oname, $_fcontent); unset( $_fcontent ); return $ret; } }