summaryrefslogtreecommitdiffstats
path: root/admin/survey/minify/lib/Minify/ClosureCompiler.php
blob: e95ebc33a6d0ab7ffd379a6ebc21ef4f6b3eb911 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
<?php
/**
 * Class Minify_ClosureCompiler
 * @package Minify
 */

/**
 * Compress Javascript using the Closure Compiler
 *
 * You must set $jarFile and $tempDir before calling the minify functions.
 * Also, depending on your shell's environment, you may need to specify
 * the full path to java in $javaExecutable or use putenv() to setup the
 * Java environment.
 *
 * <code>
 * Minify_ClosureCompiler::$jarFile = '/path/to/closure-compiler-20120123.jar';
 * Minify_ClosureCompiler::$tempDir = '/tmp';
 * $code = Minify_ClosureCompiler::minify(
 *   $code,
 *   array('compilation_level' => 'SIMPLE_OPTIMIZATIONS')
 * );
 *
 * --compilation_level WHITESPACE_ONLY, SIMPLE_OPTIMIZATIONS, ADVANCED_OPTIMIZATIONS
 *
 * </code>
 *
 * @package Minify
 * @author Stephen Clay <steve@mrclay.org>
 * @author Elan Ruusamäe <glen@delfi.ee>
 */
class Minify_ClosureCompiler
{
    public static $isDebug = false;

    /**
     * Filepath of the Closure Compiler jar file. This must be set before
     * calling minifyJs().
     *
     * @var string
     */
    public static $jarFile;

    /**
     * Writable temp directory. This must be set before calling minifyJs().
     *
     * @var string
     */
    public static $tempDir;

    /**
     * Filepath of "java" executable (may be needed if not in shell's PATH)
     *
     * @var string
     */
    public static $javaExecutable = 'java';

    /**
     * Default command line options passed to closure-compiler
     *
     * @var array
     */
    public static $defaultOptions = array(
        'charset' => 'utf-8',
        'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
        'warning_level' => 'QUIET',
    );

    /**
     * Minify a Javascript string
     *
     * @param string $js
     * @param array $options (verbose is ignored)
     * @see https://code.google.com/p/closure-compiler/source/browse/trunk/README
     * @return string
     * @throws Minify_ClosureCompiler_Exception
     */
    public static function minify($js, $options = array())
    {
        $min = new static();

        return $min->process($js, $options);
    }

    /**
     * Process $js using $options.
     *
     * @param string $js
     * @param array $options
     * @return string
     * @throws Exception
     * @throws Minify_ClosureCompiler_Exception
     */
    public function process($js, $options)
    {
        $tmpFile = $this->dumpFile(self::$tempDir, $js);
        try {
            $result = $this->compile($tmpFile, $options);
        } catch (Exception $e) {
            unlink($tmpFile);
            throw $e;
        }
        unlink($tmpFile);

        return $result;
    }

    /**
     * @param string $tmpFile
     * @param array $options
     * @return string
     * @throws Minify_ClosureCompiler_Exception
     */
    protected function compile($tmpFile, $options)
    {
        $command = $this->getCommand($options, $tmpFile);

        return implode("\n", $this->shell($command));
    }

    /**
     * @param array $userOptions
     * @param string $tmpFile
     * @return string
     */
    protected function getCommand($userOptions, $tmpFile)
    {
        $args = array_merge(
            $this->getCompilerCommandLine(),
            $this->getOptionsCommandLine($userOptions)
        );

        return implode(' ', $args) . ' ' . escapeshellarg($tmpFile);
    }

    /**
     * @return array
     * @throws Minify_ClosureCompiler_Exception
     */
    protected function getCompilerCommandLine()
    {
        $this->checkJar(self::$jarFile);
        $server = array(
            self::$javaExecutable,
            '-jar',
            escapeshellarg(self::$jarFile)
        );

        return $server;
    }

    /**
     * @param array $userOptions
     * @return array
     */
    protected function getOptionsCommandLine($userOptions)
    {
        $args = array();

        $options = array_merge(
            static::$defaultOptions,
            $userOptions
        );

        foreach ($options as $key => $value) {
            $args[] = "--{$key} " . escapeshellarg($value);
        }

        return $args;
    }

    /**
     * @param string $jarFile
     * @throws Minify_ClosureCompiler_Exception
     */
    protected function checkJar($jarFile)
    {
        if (!is_file($jarFile)) {
            throw new Minify_ClosureCompiler_Exception('$jarFile(' . $jarFile . ') is not a valid file.');
        }
        if (!is_readable($jarFile)) {
            throw new Minify_ClosureCompiler_Exception('$jarFile(' . $jarFile . ') is not readable.');
        }
    }

    /**
     * @param string $tempDir
     * @throws Minify_ClosureCompiler_Exception
     */
    protected function checkTempdir($tempDir)
    {
        if (!is_dir($tempDir)) {
            throw new Minify_ClosureCompiler_Exception('$tempDir(' . $tempDir . ') is not a valid direcotry.');
        }
        if (!is_writable($tempDir)) {
            throw new Minify_ClosureCompiler_Exception('$tempDir(' . $tempDir . ') is not writable.');
        }
    }

    /**
     * Write $content to a temporary file residing in $dir.
     *
     * @param string $dir
     * @param string $content
     * @return string
     * @throws Minify_ClosureCompiler_Exception
     */
    protected function dumpFile($dir, $content)
    {
        $this->checkTempdir($dir);
        $tmpFile = tempnam($dir, 'cc_');
        if (!$tmpFile) {
            throw new Minify_ClosureCompiler_Exception('Could not create temp file in "' . $dir . '".');
        }
        file_put_contents($tmpFile, $content);

        return $tmpFile;
    }

    /**
     * Execute command, throw if exit code is not in $expectedCodes array
     *
     * @param string $command
     * @param array $expectedCodes
     * @return mixed
     * @throws Minify_ClosureCompiler_Exception
     */
    protected function shell($command, $expectedCodes = array(0))
    {
        exec($command, $output, $result_code);
        if (!in_array($result_code, $expectedCodes)) {
            throw new Minify_ClosureCompiler_Exception("Unpexpected return code: $result_code");
        }

        return $output;
    }
}

class Minify_ClosureCompiler_Exception extends Exception
{
}