3 * jsmin.php - PHP implementation of Douglas Crockford's JSMin.
5 * This is a direct port of jsmin.c to PHP with a few PHP performance tweaks and
6 * modifications to preserve some comments (see below). Also, rather than using
7 * stdin/stdout, JSMin::minify() accepts a string as input and returns another
10 * Comments containing IE conditional compilation are preserved, as are multi-line
11 * comments that begin with "/*!" (for documentation purposes). In the latter case
12 * newlines are inserted around the comment to enhance readability.
14 * PHP 5 or higher is required.
16 * Permission is hereby granted to use this version of the library under the
17 * same terms as jsmin.c, which has the following license:
20 * Copyright (c) 2002 Douglas Crockford (www.crockford.com)
22 * Permission is hereby granted, free of charge, to any person obtaining a copy of
23 * this software and associated documentation files (the "Software"), to deal in
24 * the Software without restriction, including without limitation the rights to
25 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
26 * of the Software, and to permit persons to whom the Software is furnished to do
27 * so, subject to the following conditions:
29 * The above copyright notice and this permission notice shall be included in all
30 * copies or substantial portions of the Software.
32 * The Software shall be used for Good, not Evil.
34 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
44 * @author Ryan Grove <ryan@wonko.com> (PHP port)
45 * @author Steve Clay <steve@mrclay.org> (modifications + cleanup)
46 * @author Andrea Giammarchi <http://www.3site.eu> (spaceBeforeRegExp)
47 * @copyright 2002 Douglas Crockford <douglas@crockford.com> (jsmin.c)
48 * @copyright 2008 Ryan Grove <ryan@wonko.com> (PHP port)
49 * @license http://opensource.org/licenses/mit-license.php MIT License
50 * @link http://code.google.com/p/jsmin-php/
56 const ACTION_KEEP_A = 1;
57 const ACTION_DELETE_A = 2;
58 const ACTION_DELETE_A_B = 3;
62 protected $input = '';
63 protected $inputIndex = 0;
64 protected $inputLength = 0;
65 protected $lookAhead = null;
66 protected $output = '';
71 * @param string $js Javascript to be minified
74 public static function minify($js)
76 $jsmin = new JSMin($js);
83 public function __construct($input)
85 $this->input = str_replace("\r\n", "\n", $input);
86 $this->inputLength = strlen($this->input);
90 * Perform minification, return result
94 if ($this->output !== '') { // min already run
97 $this->action(self::ACTION_DELETE_A_B);
99 while ($this->a !== null) {
100 // determine next command
101 $command = self::ACTION_KEEP_A; // default
102 if ($this->a === ' ') {
103 if (! $this->isAlphaNum($this->b)) {
104 $command = self::ACTION_DELETE_A;
106 } elseif ($this->a === "\n") {
107 if ($this->b === ' ') {
108 $command = self::ACTION_DELETE_A_B;
109 } elseif (false === strpos('{[(+-', $this->b)
110 && ! $this->isAlphaNum($this->b)) {
111 $command = self::ACTION_DELETE_A;
113 } elseif (! $this->isAlphaNum($this->a)) {
115 || ($this->b === "\n"
116 && (false === strpos('}])+-"\'', $this->a)))) {
117 $command = self::ACTION_DELETE_A_B;
120 $this->action($command);
122 $this->output = trim($this->output);
123 return $this->output;
127 * ACTION_KEEP_A = Output A. Copy B to A. Get the next B.
128 * ACTION_DELETE_A = Copy B to A. Get the next B.
129 * ACTION_DELETE_A_B = Get the next B.
131 protected function action($command)
134 case self::ACTION_KEEP_A:
135 $this->output .= $this->a;
137 case self::ACTION_DELETE_A:
139 if ($this->a === "'" || $this->a === '"') { // string literal
140 $str = $this->a; // in case needed for exception
142 $this->output .= $this->a;
143 $this->a = $this->get();
144 if ($this->a === $this->b) { // end quote
147 if (ord($this->a) <= self::ORD_LF) {
148 throw new JSMin_UnterminatedStringException(
149 'Unterminated String: ' . var_export($str, true));
152 if ($this->a === '\\') {
153 $this->output .= $this->a;
154 $this->a = $this->get();
160 case self::ACTION_DELETE_A_B:
161 $this->b = $this->next();
162 if ($this->b === '/' && $this->isRegexpLiteral()) { // RegExp literal
163 $this->output .= $this->a . $this->b;
164 $pattern = '/'; // in case needed for exception
166 $this->a = $this->get();
167 $pattern .= $this->a;
168 if ($this->a === '/') { // end pattern
169 break; // while (true)
170 } elseif ($this->a === '\\') {
171 $this->output .= $this->a;
172 $this->a = $this->get();
173 $pattern .= $this->a;
174 } elseif (ord($this->a) <= self::ORD_LF) {
175 throw new JSMin_UnterminatedRegExpException(
176 'Unterminated RegExp: '. var_export($pattern, true));
178 $this->output .= $this->a;
180 $this->b = $this->next();
182 // end case ACTION_DELETE_A_B
186 protected function isRegexpLiteral()
188 if (false !== strpos("\n{;(,=:[!&|?", $this->a)) { // we aren't dividing
191 if (' ' === $this->a) {
192 $length = strlen($this->output);
193 if ($length < 2) { // weird edge case
196 // you can't divide a keyword
197 if (preg_match('/(?:case|else|in|return|typeof)$/', $this->output, $m)) {
198 if ($this->output === $m[0]) { // odd but could happen
201 // make sure it's a keyword, not end of an identifier
202 $charBeforeKeyword = substr($this->output, $length - strlen($m[0]) - 1, 1);
203 if (! $this->isAlphaNum($charBeforeKeyword)) {
212 * Get next char. Convert ctrl char to space.
214 protected function get()
216 $c = $this->lookAhead;
217 $this->lookAhead = null;
219 if ($this->inputIndex < $this->inputLength) {
220 $c = $this->input[$this->inputIndex];
221 $this->inputIndex += 1;
226 if ($c === "\r" || $c === "\n") {
229 if (ord($c) < self::ORD_SPACE) { // control char
236 * Get next char. If is ctrl character, translate to a space or newline.
238 protected function peek()
240 $this->lookAhead = $this->get();
241 return $this->lookAhead;
245 * Is $c a letter, digit, underscore, dollar sign, escape, or non-ASCII?
247 protected function isAlphaNum($c)
249 return (preg_match('/^[0-9a-zA-Z_\\$\\\\]$/', $c) || ord($c) > 126);
252 protected function singleLineComment()
258 if (ord($get) <= self::ORD_LF) { // EOL reached
259 // if IE conditional comment
260 if (preg_match('/^\\/@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
261 return "/{$comment}";
268 protected function multipleLineComment()
275 if ($this->peek() === '/') { // end of comment reached
277 // if comment preserved by YUI Compressor
278 if (0 === strpos($comment, '!')) {
279 return "\n/*" . substr($comment, 1) . "*/\n";
281 // if IE conditional comment
282 if (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
283 return "/*{$comment}*/";
287 } elseif ($get === null) {
288 throw new JSMin_UnterminatedCommentException('Unterminated Comment: ' . var_export('/*' . $comment, true));
295 * Get the next character, skipping over comments.
296 * Some comments may be preserved.
298 protected function next()
304 switch ($this->peek()) {
305 case '/': return $this->singleLineComment();
306 case '*': return $this->multipleLineComment();
307 default: return $get;
312 class JSMin_UnterminatedStringException extends Exception {}
313 class JSMin_UnterminatedCommentException extends Exception {}
314 class JSMin_UnterminatedRegExpException extends Exception {}