* Minify_YUICompressor::$jarFile = '/path/to/yuicompressor-2.3.5.jar'; * Minify_YUICompressor::$tempDir = '/tmp'; * $code = Minify_YUICompressor::minifyJs( * $code * ,array('nomunge' => true, 'line-break' => 1000) * ); * * * @todo unit tests, $options docs * * @package Minify * @author Stephen Clay */ class Minify_YUICompressor { /** * Filepath of the YUI Compressor jar file. This must be set before * calling minifyJs() or minifyCss(). * * @var string */ static public $jarFile = null; /** * Writable temp directory. This must be set before calling minifyJs() * or minifyCss(). * * @var string */ static public $tempDir = null; /** * Filepath of "java" executable (may be needed if not in shell's PATH) * * @var string */ static public $javaExecutable = 'java'; /** * Minify a Javascript string * * @param string $js * * @param array $options (verbose is ignored) * * @see http://www.julienlecomte.net/yuicompressor/README * * @return string */ static public function minifyJs($js, $options = array()) { return self::_minify('js', $js, $options); } /** * Minify a CSS string * * @param string $css * * @param array $options (verbose is ignored) * * @see http://www.julienlecomte.net/yuicompressor/README * * @return string */ static public function minifyCss($css, $options = array()) { return self::_minify('css', $css, $options); } private static function _minify($type, $content, $options) { self::_prepare(); if (! ($tmpFile = tempnam(self::$tempDir, 'yuic_'))) { throw new Exception('Minify_YUICompressor : could not create temp file.'); } file_put_contents($tmpFile, $content); @chmod($tmpFile, 0777); exec(self::_getCmd($options, $type, $tmpFile), $output, $return); unlink($tmpFile); return implode("\n", $output); } private static function _getCmd($userOptions, $type, $tmpFile) { $o = array_merge( array( 'charset' => '' ,'line-break' => 5000 ,'type' => $type ,'nomunge' => false ,'preserve-semi' => false ,'disable-optimizations' => false ) ,$userOptions ); $cmd = self::$javaExecutable . ' -Xmx512m -jar ' . escapeshellarg(self::$jarFile) . " --type {$type}" . (preg_match('/^[a-zA-Z\\-]+$/', $o['charset']) ? " --charset {$o['charset']}" : '') . (is_numeric($o['line-break']) && $o['line-break'] >= 0 ? ' --line-break ' . (int)$o['line-break'] : ''); if ($type === 'js') { foreach (array('nomunge', 'preserve-semi', 'disable-optimizations') as $opt) { $cmd .= $o[$opt] ? " --{$opt}" : ''; } } return $cmd . ' ' . escapeshellarg($tmpFile); } private static function _prepare() { if (! is_file(self::$jarFile) || ! is_dir(self::$tempDir) || ! is_writable(self::$tempDir) ) { throw new Exception('Minify_YUICompressor : $jarFile and $tempDir must be set.'); } } }