3 * Class Minify_ClosureCompiler
8 * Compress Javascript using the Closure Compiler
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_ClosureCompiler::$jarFile = '/path/to/closure-compiler-20120123.jar';
17 * Minify_ClosureCompiler::$tempDir = '/tmp';
18 * $code = Minify_ClosureCompiler::minify(
20 * array('compilation_level' => 'SIMPLE_OPTIMIZATIONS')
23 * --compilation_level WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS
27 * @todo unit tests, $options docs
28 * @todo more options support (or should just passthru them all?)
31 * @author Stephen Clay <steve@mrclay.org>
32 * @author Elan Ruusamäe <glen@delfi.ee>
34 class Minify_ClosureCompiler {
37 * Filepath of the Closure Compiler jar file. This must be set before
42 public static $jarFile = null;
45 * Writable temp directory. This must be set before calling minifyJs().
49 public static $tempDir = null;
52 * Filepath of "java" executable (may be needed if not in shell's PATH)
56 public static $javaExecutable = 'java';
59 * Minify a Javascript string
63 * @param array $options (verbose is ignored)
65 * @see https://code.google.com/p/closure-compiler/source/browse/trunk/README
69 public static function minify($js, $options = array())
72 if (! ($tmpFile = tempnam(self::$tempDir, 'cc_'))) {
73 throw new Exception('Minify_ClosureCompiler : could not create temp file.');
75 file_put_contents($tmpFile, $js);
76 exec(self::_getCmd($options, $tmpFile), $output, $result_code);
78 if ($result_code != 0) {
79 throw new Exception('Minify_ClosureCompiler : Closure Compiler execution failed.');
81 return implode("\n", $output);
84 private static function _getCmd($userOptions, $tmpFile)
89 'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
93 $cmd = self::$javaExecutable . ' -jar ' . escapeshellarg(self::$jarFile)
94 . (preg_match('/^[\\da-zA-Z0-9\\-]+$/', $o['charset'])
95 ? " --charset {$o['charset']}"
98 foreach (array('compilation_level') as $opt) {
100 $cmd .= " --{$opt} ". escapeshellarg($o[$opt]);
103 return $cmd . ' ' . escapeshellarg($tmpFile);
106 private static function _prepare()
108 if (! is_file(self::$jarFile)) {
109 throw new Exception('Minify_ClosureCompiler : $jarFile('.self::$jarFile.') is not a valid file.');
111 if (! is_readable(self::$jarFile)) {
112 throw new Exception('Minify_ClosureCompiler : $jarFile('.self::$jarFile.') is not readable.');
114 if (! is_dir(self::$tempDir)) {
115 throw new Exception('Minify_ClosureCompiler : $tempDir('.self::$tempDir.') is not a valid direcotry.');
117 if (! is_writable(self::$tempDir)) {
118 throw new Exception('Minify_ClosureCompiler : $tempDir('.self::$tempDir.') is not writable.');
123 /* vim:ts=4:sw=4:et */