欢迎光临
我们一直在努力

YUI Compressor PHP Script

<?php
/*
模仿YUI Compressor CMD Script(http://ourtools.googlecode.com/svn-history/r10/trunk/closure-compiler/compiler.cmd)
写的PHP版小工具
author:piao2010
website:http://piao2010.com
update:2011-04-12
*/
 
//定义jar包路径
$yuicompressor_jar = "/Library/yuicompressor-2.4.2/build/yuicompressor-2.4.2.jar";
//需要压缩的文件
$source_file = $argv[1];
$cur_dir = getcwd();
$source_file = $cur_dir.DIRECTORY_SEPARATOR.$source_file;
$path_parts = pathinfo( $source_file );
//print_r($path_parts);
 
//REM 过滤文件后缀,只压缩 js css
 
if ( !preg_match('/(js)|(css)/i' , $path_parts['extension']) )
	exit('Only support js and css file ! ');
 
if ( !file_exists( $source_file ) )
	exit(' source_file does not exist ! ');
 
if ( $_ENV['JAVA_HOME'] == '' )
	exit('No JAVA_HOME! ');
 
$java = $_ENV['JAVA_HOME'] . '/bin/java';
$native2ascii = $_ENV['JAVA_HOME'] . '/bin/native2ascii';
 
//REM 生成压缩后的文件名,规则为:
//REM 1. 文件名有.source时: filename.source.js -> filename.js
//REM 2. 其它情况:filename.js -> filename-min.js
 
if ( strpos( $path_parts['filename'] , '.source' ) ) {
	$tmp = str_replace( '.source' , '.', $path_parts['filename']);
	$result_file = $tmp.$path_parts['extension'];
}
else $result_file = $path_parts['filename'].'-min.'.$path_parts['extension'];
 
$result_file = $cur_dir.DIRECTORY_SEPARATOR.$result_file;
 
echo $source_file."n";
echo $result_file."n";
 
$cmd = $java." -jar ".$yuicompressor_jar.' '.$source_file." --charset=gb18030 -o ".$result_file;
echo $cmd."n";
system( $cmd );
@copy( $result_file , $result_file.'_bak' ) or exit ( 'Copy bak file failed! ');
 
//REM 下面解决编码问题:当 js 文件的编码与页面编码不一致时,非 ascii 字符会导致乱码,处理办法是:
//REM 1. 首先调用 native2ascii.exe 将非 ascii 字符转换为 uxxxx 即可
 
$cmd2 = $native2ascii.' -encoding GB18030 '.$result_file.'_bak '.$result_file;
echo $cmd2."n";
system( $cmd2 );
@unlink( $result_file.'_bak' ) or exit ( 'Remove bak file failed! ');
 
//REM 2. 对于 css 文件,还需要将 uxxxx 中的 u 去掉(css 只认识xxxx)
 
if ( $path_parts['extension'] == 'css' ) {
	$content = file_get_contents( $result_file );
	$content = str_replace( "u" , "" , $content );
	file_put_contents( $result_file , $content );
}
 
echo "Seems finished ! ";
?>

 

赞(0)
版权归原作者所有,如有侵权请告知。达维营-前端网 » YUI Compressor PHP Script

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址