Minifier.php 17 KB

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