3 * Class Minify_YUICompressor
8 * Compress Javascript/CSS using the YUI Compressor
10 * You must set $jarFile and $tempDir before calling the minify functions.
11 * Also, depending on your shell's environment, you may need to specify
12 * the full path to java in $javaExecutable or use putenv() to setup the
16 * Minify_YUICompressor::$jarFile = '/path/to/yuicompressor-2.3.5.jar';
17 * Minify_YUICompressor::$tempDir = '/tmp';
18 * $code = Minify_YUICompressor::minifyJs(
20 * ,array('nomunge' => true, 'line-break' => 1000)
24 * @todo unit tests, $options docs
27 * @author Stephen Clay <steve@mrclay.org>
29 class Minify_YUICompressor {
32 * Filepath of the YUI Compressor jar file. This must be set before
33 * calling minifyJs() or minifyCss().
37 public static $jarFile = null;
40 * Writable temp directory. This must be set before calling minifyJs()
45 public static $tempDir = null;
48 * Filepath of "java" executable (may be needed if not in shell's PATH)
52 public static $javaExecutable = 'java';
55 * Minify a Javascript string
59 * @param array $options (verbose is ignored)
61 * @see http://www.julienlecomte.net/yuicompressor/README
65 public static function minifyJs($js, $options = array())
67 return self::_minify('js', $js, $options);
75 * @param array $options (verbose is ignored)
77 * @see http://www.julienlecomte.net/yuicompressor/README
81 public static function minifyCss($css, $options = array())
83 return self::_minify('css', $css, $options);
86 private static function _minify($type, $content, $options)
89 if (! ($tmpFile = tempnam(self::$tempDir, 'yuic_'))) {
90 throw new Exception('Minify_YUICompressor : could not create temp file.');
92 file_put_contents($tmpFile, $content);
93 exec(self::_getCmd($options, $type, $tmpFile), $output);
95 return implode("\n", $output);
98 private static function _getCmd($userOptions, $type, $tmpFile)
103 ,'line-break' => 5000
106 ,'preserve-semi' => false
107 ,'disable-optimizations' => false
111 $cmd = self::$javaExecutable . ' -jar ' . escapeshellarg(self::$jarFile)
113 . (preg_match('/^[a-zA-Z\\-]+$/', $o['charset'])
114 ? " --charset {$o['charset']}"
116 . (is_numeric($o['line-break']) && $o['line-break'] >= 0
117 ? ' --line-break ' . (int)$o['line-break']
119 if ($type === 'js') {
120 foreach (array('nomunge', 'preserve-semi', 'disable-optimizations') as $opt) {
126 return $cmd . ' ' . escapeshellarg($tmpFile);
129 private static function _prepare()
131 if (! is_file(self::$jarFile)
132 || ! is_dir(self::$tempDir)
133 || ! is_writable(self::$tempDir)
135 throw new Exception('Minify_YUICompressor : $jarFile and $tempDir must be set.');