1 | <?php |
---|
2 | /* |
---|
3 | * This file is part of the JShrink package. |
---|
4 | * |
---|
5 | * (c) Robert Hafner <tedivm@tedivm.com> |
---|
6 | * |
---|
7 | * For the full copyright and license information, please view the LICENSE |
---|
8 | * file that was distributed with this source code. |
---|
9 | */ |
---|
10 | |
---|
11 | /** |
---|
12 | * JShrink |
---|
13 | * |
---|
14 | * |
---|
15 | * @package JShrink |
---|
16 | * @author Robert Hafner <tedivm@tedivm.com> |
---|
17 | */ |
---|
18 | |
---|
19 | namespace JShrink; |
---|
20 | |
---|
21 | /** |
---|
22 | * Minifier |
---|
23 | * |
---|
24 | * Usage - Minifier::minify($js); |
---|
25 | * Usage - Minifier::minify($js, $options); |
---|
26 | * Usage - Minifier::minify($js, array('flaggedComments' => false)); |
---|
27 | * |
---|
28 | * @package JShrink |
---|
29 | * @author Robert Hafner <tedivm@tedivm.com> |
---|
30 | * @license http://www.opensource.org/licenses/bsd-license.php BSD License |
---|
31 | */ |
---|
32 | class Minifier |
---|
33 | { |
---|
34 | /** |
---|
35 | * The input javascript to be minified. |
---|
36 | * |
---|
37 | * @var string |
---|
38 | */ |
---|
39 | protected $input; |
---|
40 | |
---|
41 | /** |
---|
42 | * The location of the character (in the input string) that is next to be |
---|
43 | * processed. |
---|
44 | * |
---|
45 | * @var int |
---|
46 | */ |
---|
47 | protected $index = 0; |
---|
48 | |
---|
49 | /** |
---|
50 | * The first of the characters currently being looked at. |
---|
51 | * |
---|
52 | * @var string |
---|
53 | */ |
---|
54 | protected $a = ''; |
---|
55 | |
---|
56 | /** |
---|
57 | * The next character being looked at (after a); |
---|
58 | * |
---|
59 | * @var string |
---|
60 | */ |
---|
61 | protected $b = ''; |
---|
62 | |
---|
63 | /** |
---|
64 | * This character is only active when certain look ahead actions take place. |
---|
65 | * |
---|
66 | * @var string |
---|
67 | */ |
---|
68 | protected $c; |
---|
69 | |
---|
70 | /** |
---|
71 | * Contains the options for the current minification process. |
---|
72 | * |
---|
73 | * @var array |
---|
74 | */ |
---|
75 | protected $options; |
---|
76 | |
---|
77 | /** |
---|
78 | * Contains the default options for minification. This array is merged with |
---|
79 | * the one passed in by the user to create the request specific set of |
---|
80 | * options (stored in the $options attribute). |
---|
81 | * |
---|
82 | * @var array |
---|
83 | */ |
---|
84 | protected static $defaultOptions = array('flaggedComments' => true); |
---|
85 | |
---|
86 | /** |
---|
87 | * Contains lock ids which are used to replace certain code patterns and |
---|
88 | * prevent them from being minified |
---|
89 | * |
---|
90 | * @var array |
---|
91 | */ |
---|
92 | protected $locks = array(); |
---|
93 | |
---|
94 | /** |
---|
95 | * Takes a string containing javascript and removes unneeded characters in |
---|
96 | * order to shrink the code without altering it's functionality. |
---|
97 | * |
---|
98 | * @param string $js The raw javascript to be minified |
---|
99 | * @param array $options Various runtime options in an associative array |
---|
100 | * @throws \Exception |
---|
101 | * @return bool|string |
---|
102 | */ |
---|
103 | public static function minify($js, $options = array()) |
---|
104 | { |
---|
105 | try { |
---|
106 | ob_start(); |
---|
107 | |
---|
108 | $jshrink = new Minifier(); |
---|
109 | $js = $jshrink->lock($js); |
---|
110 | $jshrink->minifyDirectToOutput($js, $options); |
---|
111 | |
---|
112 | // Sometimes there's a leading new line, so we trim that out here. |
---|
113 | $js = ltrim(ob_get_clean()); |
---|
114 | $js = $jshrink->unlock($js); |
---|
115 | unset($jshrink); |
---|
116 | |
---|
117 | return $js; |
---|
118 | |
---|
119 | } catch (\Exception $e) { |
---|
120 | |
---|
121 | if (isset($jshrink)) { |
---|
122 | // Since the breakdownScript function probably wasn't finished |
---|
123 | // we clean it out before discarding it. |
---|
124 | $jshrink->clean(); |
---|
125 | unset($jshrink); |
---|
126 | } |
---|
127 | |
---|
128 | // without this call things get weird, with partially outputted js. |
---|
129 | ob_end_clean(); |
---|
130 | throw $e; |
---|
131 | } |
---|
132 | } |
---|
133 | |
---|
134 | /** |
---|
135 | * Processes a javascript string and outputs only the required characters, |
---|
136 | * stripping out all unneeded characters. |
---|
137 | * |
---|
138 | * @param string $js The raw javascript to be minified |
---|
139 | * @param array $options Various runtime options in an associative array |
---|
140 | */ |
---|
141 | protected function minifyDirectToOutput($js, $options) |
---|
142 | { |
---|
143 | $this->initialize($js, $options); |
---|
144 | $this->loop(); |
---|
145 | $this->clean(); |
---|
146 | } |
---|
147 | |
---|
148 | /** |
---|
149 | * Initializes internal variables, normalizes new lines, |
---|
150 | * |
---|
151 | * @param string $js The raw javascript to be minified |
---|
152 | * @param array $options Various runtime options in an associative array |
---|
153 | */ |
---|
154 | protected function initialize($js, $options) |
---|
155 | { |
---|
156 | $this->options = array_merge(static::$defaultOptions, $options); |
---|
157 | $js = str_replace("\r\n", "\n", $js); |
---|
158 | $js = str_replace('/**/', '', $js); |
---|
159 | $this->input = str_replace("\r", "\n", $js); |
---|
160 | |
---|
161 | // We add a newline to the end of the script to make it easier to deal |
---|
162 | // with comments at the bottom of the script- this prevents the unclosed |
---|
163 | // comment error that can otherwise occur. |
---|
164 | $this->input .= PHP_EOL; |
---|
165 | |
---|
166 | // Populate "a" with a new line, "b" with the first character, before |
---|
167 | // entering the loop |
---|
168 | $this->a = "\n"; |
---|
169 | $this->b = $this->getReal(); |
---|
170 | } |
---|
171 | |
---|
172 | /** |
---|
173 | * The primary action occurs here. This function loops through the input string, |
---|
174 | * outputting anything that's relevant and discarding anything that is not. |
---|
175 | */ |
---|
176 | protected function loop() |
---|
177 | { |
---|
178 | while ($this->a !== false && !is_null($this->a) && $this->a !== '') { |
---|
179 | |
---|
180 | switch ($this->a) { |
---|
181 | // new lines |
---|
182 | case "\n": |
---|
183 | // if the next line is something that can't stand alone preserve the newline |
---|
184 | if (strpos('(-+{[@', $this->b) !== false) { |
---|
185 | echo $this->a; |
---|
186 | $this->saveString(); |
---|
187 | break; |
---|
188 | } |
---|
189 | |
---|
190 | // if B is a space we skip the rest of the switch block and go down to the |
---|
191 | // string/regex check below, resetting $this->b with getReal |
---|
192 | if ($this->b === ' ') { |
---|
193 | break; |
---|
194 | } |
---|
195 | |
---|
196 | // otherwise we treat the newline like a space |
---|
197 | |
---|
198 | case ' ': |
---|
199 | if (static::isAlphaNumeric($this->b)) { |
---|
200 | echo $this->a; |
---|
201 | } |
---|
202 | |
---|
203 | $this->saveString(); |
---|
204 | break; |
---|
205 | |
---|
206 | default: |
---|
207 | switch ($this->b) { |
---|
208 | case "\n": |
---|
209 | if (strpos('}])+-"\'`', $this->a) !== false) { |
---|
210 | echo $this->a; |
---|
211 | $this->saveString(); |
---|
212 | break; |
---|
213 | } else { |
---|
214 | if (static::isAlphaNumeric($this->a)) { |
---|
215 | echo $this->a; |
---|
216 | $this->saveString(); |
---|
217 | } |
---|
218 | } |
---|
219 | break; |
---|
220 | |
---|
221 | case ' ': |
---|
222 | if (!static::isAlphaNumeric($this->a)) { |
---|
223 | break; |
---|
224 | } |
---|
225 | |
---|
226 | default: |
---|
227 | // check for some regex that breaks stuff |
---|
228 | if ($this->a === '/' && ($this->b === '\'' || $this->b === '"' || $this->b === '`')) { |
---|
229 | $this->saveRegex(); |
---|
230 | break; |
---|
231 | } |
---|
232 | |
---|
233 | echo $this->a; |
---|
234 | $this->saveString(); |
---|
235 | break; |
---|
236 | } |
---|
237 | } |
---|
238 | |
---|
239 | // do reg check of doom |
---|
240 | $this->b = $this->getReal(); |
---|
241 | |
---|
242 | if (($this->b == '/' && strpos('(,=:[!&|?', $this->a) !== false)) { |
---|
243 | $this->saveRegex(); |
---|
244 | } |
---|
245 | |
---|
246 | } |
---|
247 | } |
---|
248 | |
---|
249 | /** |
---|
250 | * Resets attributes that do not need to be stored between requests so that |
---|
251 | * the next request is ready to go. Another reason for this is to make sure |
---|
252 | * the variables are cleared and are not taking up memory. |
---|
253 | */ |
---|
254 | protected function clean() |
---|
255 | { |
---|
256 | unset($this->input); |
---|
257 | $this->index = 0; |
---|
258 | $this->a = $this->b = ''; |
---|
259 | unset($this->c); |
---|
260 | unset($this->options); |
---|
261 | } |
---|
262 | |
---|
263 | /** |
---|
264 | * Returns the next string for processing based off of the current index. |
---|
265 | * |
---|
266 | * @return string |
---|
267 | */ |
---|
268 | protected function getChar() |
---|
269 | { |
---|
270 | // Check to see if we had anything in the look ahead buffer and use that. |
---|
271 | if (isset($this->c)) { |
---|
272 | $char = $this->c; |
---|
273 | unset($this->c); |
---|
274 | |
---|
275 | // Otherwise we start pulling from the input. |
---|
276 | } else { |
---|
277 | $char = substr($this->input, $this->index, 1); |
---|
278 | |
---|
279 | // If the next character doesn't exist return false. |
---|
280 | if (isset($char) && $char === false) { |
---|
281 | return false; |
---|
282 | } |
---|
283 | |
---|
284 | // Otherwise increment the pointer and use this char. |
---|
285 | $this->index++; |
---|
286 | } |
---|
287 | |
---|
288 | // Normalize all whitespace except for the newline character into a |
---|
289 | // standard space. |
---|
290 | if ($char !== "\n" && ord($char) < 32) { |
---|
291 | return ' '; |
---|
292 | } |
---|
293 | |
---|
294 | return $char; |
---|
295 | } |
---|
296 | |
---|
297 | /** |
---|
298 | * This function gets the next "real" character. It is essentially a wrapper |
---|
299 | * around the getChar function that skips comments. This has significant |
---|
300 | * performance benefits as the skipping is done using native functions (ie, |
---|
301 | * c code) rather than in script php. |
---|
302 | * |
---|
303 | * |
---|
304 | * @return string Next 'real' character to be processed. |
---|
305 | * @throws \RuntimeException |
---|
306 | */ |
---|
307 | protected function getReal() |
---|
308 | { |
---|
309 | $startIndex = $this->index; |
---|
310 | $char = $this->getChar(); |
---|
311 | |
---|
312 | // Check to see if we're potentially in a comment |
---|
313 | if ($char !== '/') { |
---|
314 | return $char; |
---|
315 | } |
---|
316 | |
---|
317 | $this->c = $this->getChar(); |
---|
318 | |
---|
319 | if ($this->c === '/') { |
---|
320 | return $this->processOneLineComments($startIndex); |
---|
321 | |
---|
322 | } elseif ($this->c === '*') { |
---|
323 | return $this->processMultiLineComments($startIndex); |
---|
324 | } |
---|
325 | |
---|
326 | return $char; |
---|
327 | } |
---|
328 | |
---|
329 | /** |
---|
330 | * Removed one line comments, with the exception of some very specific types of |
---|
331 | * conditional comments. |
---|
332 | * |
---|
333 | * @param int $startIndex The index point where "getReal" function started |
---|
334 | * @return string |
---|
335 | */ |
---|
336 | protected function processOneLineComments($startIndex) |
---|
337 | { |
---|
338 | $thirdCommentString = substr($this->input, $this->index, 1); |
---|
339 | |
---|
340 | // kill rest of line |
---|
341 | $this->getNext("\n"); |
---|
342 | |
---|
343 | if ($thirdCommentString == '@') { |
---|
344 | $endPoint = $this->index - $startIndex; |
---|
345 | unset($this->c); |
---|
346 | $char = "\n" . substr($this->input, $startIndex, $endPoint); |
---|
347 | } else { |
---|
348 | // first one is contents of $this->c |
---|
349 | $this->getChar(); |
---|
350 | $char = $this->getChar(); |
---|
351 | } |
---|
352 | |
---|
353 | return $char; |
---|
354 | } |
---|
355 | |
---|
356 | /** |
---|
357 | * Skips multiline comments where appropriate, and includes them where needed. |
---|
358 | * Conditional comments and "license" style blocks are preserved. |
---|
359 | * |
---|
360 | * @param int $startIndex The index point where "getReal" function started |
---|
361 | * @return bool|string False if there's no character |
---|
362 | * @throws \RuntimeException Unclosed comments will throw an error |
---|
363 | */ |
---|
364 | protected function processMultiLineComments($startIndex) |
---|
365 | { |
---|
366 | $this->getChar(); // current C |
---|
367 | $thirdCommentString = $this->getChar(); |
---|
368 | |
---|
369 | // kill everything up to the next */ if it's there |
---|
370 | if ($this->getNext('*/')) { |
---|
371 | |
---|
372 | $this->getChar(); // get * |
---|
373 | $this->getChar(); // get / |
---|
374 | $char = $this->getChar(); // get next real character |
---|
375 | |
---|
376 | // Now we reinsert conditional comments and YUI-style licensing comments |
---|
377 | if (($this->options['flaggedComments'] && $thirdCommentString === '!') |
---|
378 | || ($thirdCommentString === '@')) { |
---|
379 | |
---|
380 | // If conditional comments or flagged comments are not the first thing in the script |
---|
381 | // we need to echo a and fill it with a space before moving on. |
---|
382 | if ($startIndex > 0) { |
---|
383 | echo $this->a; |
---|
384 | $this->a = " "; |
---|
385 | |
---|
386 | // If the comment started on a new line we let it stay on the new line |
---|
387 | if ($this->input[($startIndex - 1)] === "\n") { |
---|
388 | echo "\n"; |
---|
389 | } |
---|
390 | } |
---|
391 | |
---|
392 | $endPoint = ($this->index - 1) - $startIndex; |
---|
393 | echo substr($this->input, $startIndex, $endPoint); |
---|
394 | |
---|
395 | return $char; |
---|
396 | } |
---|
397 | |
---|
398 | } else { |
---|
399 | $char = false; |
---|
400 | } |
---|
401 | |
---|
402 | if ($char === false) { |
---|
403 | throw new \RuntimeException('Unclosed multiline comment at position: ' . ($this->index - 2)); |
---|
404 | } |
---|
405 | |
---|
406 | // if we're here c is part of the comment and therefore tossed |
---|
407 | if (isset($this->c)) { |
---|
408 | unset($this->c); |
---|
409 | } |
---|
410 | |
---|
411 | return $char; |
---|
412 | } |
---|
413 | |
---|
414 | /** |
---|
415 | * Pushes the index ahead to the next instance of the supplied string. If it |
---|
416 | * is found the first character of the string is returned and the index is set |
---|
417 | * to it's position. |
---|
418 | * |
---|
419 | * @param string $string |
---|
420 | * @return string|false Returns the first character of the string or false. |
---|
421 | */ |
---|
422 | protected function getNext($string) |
---|
423 | { |
---|
424 | // Find the next occurrence of "string" after the current position. |
---|
425 | $pos = strpos($this->input, $string, $this->index); |
---|
426 | |
---|
427 | // If it's not there return false. |
---|
428 | if ($pos === false) { |
---|
429 | return false; |
---|
430 | } |
---|
431 | |
---|
432 | // Adjust position of index to jump ahead to the asked for string |
---|
433 | $this->index = $pos; |
---|
434 | |
---|
435 | // Return the first character of that string. |
---|
436 | return substr($this->input, $this->index, 1); |
---|
437 | } |
---|
438 | |
---|
439 | /** |
---|
440 | * When a javascript string is detected this function crawls for the end of |
---|
441 | * it and saves the whole string. |
---|
442 | * |
---|
443 | * @throws \RuntimeException Unclosed strings will throw an error |
---|
444 | */ |
---|
445 | protected function saveString() |
---|
446 | { |
---|
447 | $startpos = $this->index; |
---|
448 | |
---|
449 | // saveString is always called after a gets cleared, so we push b into |
---|
450 | // that spot. |
---|
451 | $this->a = $this->b; |
---|
452 | |
---|
453 | // If this isn't a string we don't need to do anything. |
---|
454 | if ($this->a !== "'" && $this->a !== '"' && $this->a !== '`') { |
---|
455 | return; |
---|
456 | } |
---|
457 | |
---|
458 | // String type is the quote used, " or ' or ` |
---|
459 | $stringType = $this->a; |
---|
460 | |
---|
461 | // Echo out that starting quote |
---|
462 | echo $this->a; |
---|
463 | |
---|
464 | // Loop until the string is done |
---|
465 | while (true) { |
---|
466 | |
---|
467 | // Grab the very next character and load it into a |
---|
468 | $this->a = $this->getChar(); |
---|
469 | |
---|
470 | switch ($this->a) { |
---|
471 | |
---|
472 | // If the string opener (single or double quote) is used |
---|
473 | // output it and break out of the while loop- |
---|
474 | // The string is finished! |
---|
475 | case $stringType: |
---|
476 | break 2; |
---|
477 | |
---|
478 | // New lines in strings without line delimiters are bad- actual |
---|
479 | // new lines will be represented by the string \n and not the actual |
---|
480 | // character, so those will be treated just fine using the switch |
---|
481 | // block below. |
---|
482 | case "\n": |
---|
483 | if ($stringType !== '`') { |
---|
484 | throw new \RuntimeException('Unclosed string at position: ' . $startpos); |
---|
485 | } else { |
---|
486 | echo $this->a; |
---|
487 | } |
---|
488 | break; |
---|
489 | |
---|
490 | // Escaped characters get picked up here. If it's an escaped new line it's not really needed |
---|
491 | case '\\': |
---|
492 | |
---|
493 | // a is a slash. We want to keep it, and the next character, |
---|
494 | // unless it's a new line. New lines as actual strings will be |
---|
495 | // preserved, but escaped new lines should be reduced. |
---|
496 | $this->b = $this->getChar(); |
---|
497 | |
---|
498 | // If b is a new line we discard a and b and restart the loop. |
---|
499 | if ($this->b === "\n") { |
---|
500 | break; |
---|
501 | } |
---|
502 | |
---|
503 | // echo out the escaped character and restart the loop. |
---|
504 | echo $this->a . $this->b; |
---|
505 | break; |
---|
506 | |
---|
507 | // Since we're not dealing with any special cases we simply |
---|
508 | // output the character and continue our loop. |
---|
509 | default: |
---|
510 | echo $this->a; |
---|
511 | } |
---|
512 | } |
---|
513 | } |
---|
514 | |
---|
515 | /** |
---|
516 | * When a regular expression is detected this function crawls for the end of |
---|
517 | * it and saves the whole regex. |
---|
518 | * |
---|
519 | * @throws \RuntimeException Unclosed regex will throw an error |
---|
520 | */ |
---|
521 | protected function saveRegex() |
---|
522 | { |
---|
523 | echo $this->a . $this->b; |
---|
524 | |
---|
525 | while (($this->a = $this->getChar()) !== false) { |
---|
526 | if ($this->a === '/') { |
---|
527 | break; |
---|
528 | } |
---|
529 | |
---|
530 | if ($this->a === '\\') { |
---|
531 | echo $this->a; |
---|
532 | $this->a = $this->getChar(); |
---|
533 | } |
---|
534 | |
---|
535 | if ($this->a === "\n") { |
---|
536 | throw new \RuntimeException('Unclosed regex pattern at position: ' . $this->index); |
---|
537 | } |
---|
538 | |
---|
539 | echo $this->a; |
---|
540 | } |
---|
541 | $this->b = $this->getReal(); |
---|
542 | } |
---|
543 | |
---|
544 | /** |
---|
545 | * Checks to see if a character is alphanumeric. |
---|
546 | * |
---|
547 | * @param string $char Just one character |
---|
548 | * @return bool |
---|
549 | */ |
---|
550 | protected static function isAlphaNumeric($char) |
---|
551 | { |
---|
552 | return preg_match('/^[\w\$\pL]$/', $char) === 1 || $char == '/'; |
---|
553 | } |
---|
554 | |
---|
555 | /** |
---|
556 | * Replace patterns in the given string and store the replacement |
---|
557 | * |
---|
558 | * @param string $js The string to lock |
---|
559 | * @return bool |
---|
560 | */ |
---|
561 | protected function lock($js) |
---|
562 | { |
---|
563 | /* lock things like <code>"asd" + ++x;</code> */ |
---|
564 | $lock = '"LOCK---' . crc32(time()) . '"'; |
---|
565 | |
---|
566 | $matches = array(); |
---|
567 | preg_match('/([+-])(\s+)([+-])/S', $js, $matches); |
---|
568 | if (empty($matches)) { |
---|
569 | return $js; |
---|
570 | } |
---|
571 | |
---|
572 | $this->locks[$lock] = $matches[2]; |
---|
573 | |
---|
574 | $js = preg_replace('/([+-])\s+([+-])/S', "$1{$lock}$2", $js); |
---|
575 | /* -- */ |
---|
576 | |
---|
577 | return $js; |
---|
578 | } |
---|
579 | |
---|
580 | /** |
---|
581 | * Replace "locks" with the original characters |
---|
582 | * |
---|
583 | * @param string $js The string to unlock |
---|
584 | * @return bool |
---|
585 | */ |
---|
586 | protected function unlock($js) |
---|
587 | { |
---|
588 | if (empty($this->locks)) { |
---|
589 | return $js; |
---|
590 | } |
---|
591 | |
---|
592 | foreach ($this->locks as $lock => $replacement) { |
---|
593 | $js = str_replace($lock, $replacement, $js); |
---|
594 | } |
---|
595 | |
---|
596 | return $js; |
---|
597 | } |
---|
598 | |
---|
599 | } |
---|