3 * Minify a file or set of files
6 require_once( dirname( __FILE__
) . '/Maintenance.php' );
8 class MinifyScript
extends Maintenance
{
11 public function __construct() {
12 parent
::__construct();
13 $this->addOption( 'outfile',
14 'File for output. Only a single file may be specified for input.',
16 $this->addOption( 'outdir',
17 "Directory for output. If this is not specified, and neither is --outfile, then the\n" .
18 "output files will be sent to the same directories as the input files.",
20 $this->mDescription
= "Minify a file or set of files.\n\n" .
21 "If --outfile is not specified, then the output file names will have a .min extension\n" .
22 "added, e.g. jquery.js -> jquery.min.js.";
26 public function execute() {
27 if ( !count( $this->mArgs
) ) {
28 $this->error( "minify.php: At least one input file must be specified." );
32 if ( $this->hasOption( 'outfile' ) ) {
33 if ( count( $this->mArgs
) > 1 ) {
34 $this->error( '--outfile may only be used with a single input file.' );
39 $this->minify( $this->getArg( 0 ), $this->getOption( 'outfile' ) );
43 $outDir = $this->getOption( 'outdir', false );
45 foreach ( $this->mArgs
as $arg ) {
46 $inPath = realpath( $arg );
47 $inName = basename( $inPath );
48 $inDir = dirname( $inPath );
50 if ( strpos( $inName, '.min.' ) !== false ) {
51 $this->error( "Skipping $inName\n" );
55 if ( !file_exists( $inPath ) ) {
56 $this->error( "File does not exist: $arg", true );
59 $extension = $this->getExtension( $inName );
60 $outName = substr( $inName, 0, -strlen( $extension ) ) . 'min.' . $extension;
61 if ( $outDir === false ) {
62 $outPath = $inDir . '/' . $outName;
64 $outPath = $outDir . '/' . $outName;
67 $this->minify( $inPath, $outPath );
71 public function getExtension( $fileName ) {
72 $dotPos = strrpos( $fileName, '.' );
73 if ( $dotPos === false ) {
74 $this->error( "No file extension, cannot determine type: $arg" );
77 return substr( $fileName, $dotPos +
1 );
80 public function minify( $inPath, $outPath ) {
81 $extension = $this->getExtension( $inPath );
82 $this->output( basename( $inPath ) . ' -> ' . basename( $outPath ) . '...' );
84 $inText = file_get_contents( $inPath );
85 if ( $inText === false ) {
86 $this->error( "Unable to open file $inPath for reading." );
89 $outFile = fopen( $outPath, 'w' );
91 $this->error( "Unable to open file $outPath for writing." );
95 switch ( $extension ) {
97 $outText = JSMin
::minify( $inText );
100 $outText = CSSMin
::minify( $inText );
103 $this->error( "No minifier defined for extension \"$extension\"" );
106 fwrite( $outFile, $outText );
108 $this->output( " ok\n" );
112 $maintClass = 'MinifyScript';
113 require_once( DO_MAINTENANCE
);