1: <?php
2: /**
3: * jsmin.php - PHP implementation of Douglas Crockford's JSMin.
4: *
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
8: * string as output.
9: *
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.
13: *
14: * PHP 5 or higher is required.
15: *
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:
18: *
19: * --
20: * Copyright (c) 2002 Douglas Crockford (www.crockford.com)
21: *
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:
28: *
29: * The above copyright notice and this permission notice shall be included in all
30: * copies or substantial portions of the Software.
31: *
32: * The Software shall be used for Good, not Evil.
33: *
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
40: * SOFTWARE.
41: * --
42: *
43: * @package JSMin
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/
51: */
52:
53: class JSMin {
54: const ORD_LF = 10;
55: const ORD_SPACE = 32;
56: const ACTION_KEEP_A = 1;
57: const ACTION_DELETE_A = 2;
58: const ACTION_DELETE_A_B = 3;
59:
60: protected $a = "\n";
61: protected $b = '';
62: protected $input = '';
63: protected $inputIndex = 0;
64: protected $inputLength = 0;
65: protected $lookAhead = null;
66: protected $output = '';
67:
68: /**
69: * Minify Javascript
70: *
71: * @param string $js Javascript to be minified
72: * @return string
73: */
74: public static function minify($js)
75: {
76: $jsmin = new JSMin($js);
77: return $jsmin->min();
78: }
79:
80: /**
81: * Setup process
82: */
83: public function __construct($input)
84: {
85: $this->input = str_replace("\r\n", "\n", $input);
86: $this->inputLength = strlen($this->input);
87: }
88:
89: /**
90: * Perform minification, return result
91: */
92: public function min()
93: {
94: if ($this->output !== '') { // min already run
95: return $this->output;
96: }
97: $this->action(self::ACTION_DELETE_A_B);
98:
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;
105: }
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;
112: }
113: } elseif (! $this->isAlphaNum($this->a)) {
114: if ($this->b === ' '
115: || ($this->b === "\n"
116: && (false === strpos('}])+-"\'', $this->a)))) {
117: $command = self::ACTION_DELETE_A_B;
118: }
119: }
120: $this->action($command);
121: }
122: $this->output = trim($this->output);
123: return $this->output;
124: }
125:
126: /**
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.
130: */
131: protected function action($command)
132: {
133: switch ($command) {
134: case self::ACTION_KEEP_A:
135: $this->output .= $this->a;
136: // fallthrough
137: case self::ACTION_DELETE_A:
138: $this->a = $this->b;
139: if ($this->a === "'" || $this->a === '"') { // string literal
140: $str = $this->a; // in case needed for exception
141: while (true) {
142: $this->output .= $this->a;
143: $this->a = $this->get();
144: if ($this->a === $this->b) { // end quote
145: break;
146: }
147: if (ord($this->a) <= self::ORD_LF) {
148: throw new JSMin_UnterminatedStringException(
149: 'Unterminated String: ' . var_export($str, true));
150: }
151: $str .= $this->a;
152: if ($this->a === '\\') {
153: $this->output .= $this->a;
154: $this->a = $this->get();
155: $str .= $this->a;
156: }
157: }
158: }
159: // fallthrough
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
165: while (true) {
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));
177: }
178: $this->output .= $this->a;
179: }
180: $this->b = $this->next();
181: }
182: // end case ACTION_DELETE_A_B
183: }
184: }
185:
186: protected function isRegexpLiteral()
187: {
188: if (false !== strpos("\n{;(,=:[!&|?", $this->a)) { // we aren't dividing
189: return true;
190: }
191: if (' ' === $this->a) {
192: $length = strlen($this->output);
193: if ($length < 2) { // weird edge case
194: return true;
195: }
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
199: return true;
200: }
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)) {
204: return true;
205: }
206: }
207: }
208: return false;
209: }
210:
211: /**
212: * Get next char. Convert ctrl char to space.
213: */
214: protected function get()
215: {
216: $c = $this->lookAhead;
217: $this->lookAhead = null;
218: if ($c === null) {
219: if ($this->inputIndex < $this->inputLength) {
220: $c = $this->input[$this->inputIndex];
221: $this->inputIndex += 1;
222: } else {
223: return null;
224: }
225: }
226: if ($c === "\r" || $c === "\n") {
227: return "\n";
228: }
229: if (ord($c) < self::ORD_SPACE) { // control char
230: return ' ';
231: }
232: return $c;
233: }
234:
235: /**
236: * Get next char. If is ctrl character, translate to a space or newline.
237: */
238: protected function peek()
239: {
240: $this->lookAhead = $this->get();
241: return $this->lookAhead;
242: }
243:
244: /**
245: * Is $c a letter, digit, underscore, dollar sign, escape, or non-ASCII?
246: */
247: protected function isAlphaNum($c)
248: {
249: return (preg_match('/^[0-9a-zA-Z_\\$\\\\]$/', $c) || ord($c) > 126);
250: }
251:
252: protected function singleLineComment()
253: {
254: $comment = '';
255: while (true) {
256: $get = $this->get();
257: $comment .= $get;
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}";
262: }
263: return $get;
264: }
265: }
266: }
267:
268: protected function multipleLineComment()
269: {
270: $this->get();
271: $comment = '';
272: while (true) {
273: $get = $this->get();
274: if ($get === '*') {
275: if ($this->peek() === '/') { // end of comment reached
276: $this->get();
277: // if comment preserved by YUI Compressor
278: if (0 === strpos($comment, '!')) {
279: return "\n/*" . substr($comment, 1) . "*/\n";
280: }
281: // if IE conditional comment
282: if (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
283: return "/*{$comment}*/";
284: }
285: return ' ';
286: }
287: } elseif ($get === null) {
288: throw new JSMin_UnterminatedCommentException('Unterminated Comment: ' . var_export('/*' . $comment, true));
289: }
290: $comment .= $get;
291: }
292: }
293:
294: /**
295: * Get the next character, skipping over comments.
296: * Some comments may be preserved.
297: */
298: protected function next()
299: {
300: $get = $this->get();
301: if ($get !== '/') {
302: return $get;
303: }
304: switch ($this->peek()) {
305: case '/': return $this->singleLineComment();
306: case '*': return $this->multipleLineComment();
307: default: return $get;
308: }
309: }
310: }
311:
312: class JSMin_UnterminatedStringException extends Exception {}
313: class JSMin_UnterminatedCommentException extends Exception {}
314: class JSMin_UnterminatedRegExpException extends Exception {}
315: