JSMin.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. /**
  3. * JSMin.php - modified PHP implementation of Douglas Crockford's JSMin.
  4. *
  5. * <code>
  6. * $minifiedJs = JSMin::minify($js);
  7. * </code>
  8. *
  9. * This is a modified port of jsmin.c. Improvements:
  10. *
  11. * Does not choke on some regexp literals containing quote characters. E.g. /'/
  12. *
  13. * Spaces are preserved after some add/sub operators, so they are not mistakenly
  14. * converted to post-inc/dec. E.g. a + ++b -> a+ ++b
  15. *
  16. * Preserves multi-line comments that begin with /*!
  17. *
  18. * PHP 5 or higher is required.
  19. *
  20. * Permission is hereby granted to use this version of the library under the
  21. * same terms as jsmin.c, which has the following license:
  22. *
  23. * --
  24. * Copyright (c) 2002 Douglas Crockford (www.crockford.com)
  25. *
  26. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  27. * this software and associated documentation files (the "Software"), to deal in
  28. * the Software without restriction, including without limitation the rights to
  29. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  30. * of the Software, and to permit persons to whom the Software is furnished to do
  31. * so, subject to the following conditions:
  32. *
  33. * The above copyright notice and this permission notice shall be included in all
  34. * copies or substantial portions of the Software.
  35. *
  36. * The Software shall be used for Good, not Evil.
  37. *
  38. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  39. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  42. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  43. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  44. * SOFTWARE.
  45. * --
  46. *
  47. * @package JSMin
  48. * @author Ryan Grove <ryan@wonko.com> (PHP port)
  49. * @author Steve Clay <steve@mrclay.org> (modifications + cleanup)
  50. * @author Andrea Giammarchi <http://www.3site.eu> (spaceBeforeRegExp)
  51. * @copyright 2002 Douglas Crockford <douglas@crockford.com> (jsmin.c)
  52. * @copyright 2008 Ryan Grove <ryan@wonko.com> (PHP port)
  53. * @license http://opensource.org/licenses/mit-license.php MIT License
  54. * @link http://code.google.com/p/jsmin-php/
  55. */
  56. class JSMin {
  57. const ORD_LF = 10;
  58. const ORD_SPACE = 32;
  59. const ACTION_KEEP_A = 1;
  60. const ACTION_DELETE_A = 2;
  61. const ACTION_DELETE_A_B = 3;
  62. protected $a = "\n";
  63. protected $b = '';
  64. protected $input = '';
  65. protected $inputIndex = 0;
  66. protected $inputLength = 0;
  67. protected $lookAhead = null;
  68. protected $output = '';
  69. protected $lastByteOut = '';
  70. /**
  71. * Minify Javascript.
  72. *
  73. * @param string $js Javascript to be minified
  74. *
  75. * @return string
  76. */
  77. public static function minify($js)
  78. {
  79. $jsmin = new JSMin($js);
  80. return $jsmin->min();
  81. }
  82. /**
  83. * @param string $input
  84. */
  85. public function __construct($input)
  86. {
  87. $this->input = $input;
  88. }
  89. /**
  90. * Perform minification, return result
  91. *
  92. * @return string
  93. */
  94. public function min()
  95. {
  96. if ($this->output !== '') { // min already run
  97. return $this->output;
  98. }
  99. $mbIntEnc = null;
  100. if (function_exists('mb_strlen') && ((int)ini_get('mbstring.func_overload') & 2)) {
  101. $mbIntEnc = mb_internal_encoding();
  102. mb_internal_encoding('8bit');
  103. }
  104. $this->input = str_replace("\r\n", "\n", $this->input);
  105. $this->inputLength = strlen($this->input);
  106. $this->action(self::ACTION_DELETE_A_B);
  107. while ($this->a !== null) {
  108. // determine next command
  109. $command = self::ACTION_KEEP_A; // default
  110. if ($this->a === ' ') {
  111. if (($this->lastByteOut === '+' || $this->lastByteOut === '-')
  112. && ($this->b === $this->lastByteOut)) {
  113. // Don't delete this space. If we do, the addition/subtraction
  114. // could be parsed as a post-increment
  115. } elseif (! $this->isAlphaNum($this->b)) {
  116. $command = self::ACTION_DELETE_A;
  117. }
  118. } elseif ($this->a === "\n") {
  119. if ($this->b === ' ') {
  120. $command = self::ACTION_DELETE_A_B;
  121. // in case of mbstring.func_overload & 2, must check for null b,
  122. // otherwise mb_strpos will give WARNING
  123. } elseif ($this->b === null
  124. || (false === strpos('{[(+-', $this->b)
  125. && ! $this->isAlphaNum($this->b))) {
  126. $command = self::ACTION_DELETE_A;
  127. }
  128. } elseif (! $this->isAlphaNum($this->a)) {
  129. if ($this->b === ' '
  130. || ($this->b === "\n"
  131. && (false === strpos('}])+-"\'', $this->a)))) {
  132. $command = self::ACTION_DELETE_A_B;
  133. }
  134. }
  135. $this->action($command);
  136. }
  137. $this->output = trim($this->output);
  138. if ($mbIntEnc !== null) {
  139. mb_internal_encoding($mbIntEnc);
  140. }
  141. return $this->output;
  142. }
  143. /**
  144. * ACTION_KEEP_A = Output A. Copy B to A. Get the next B.
  145. * ACTION_DELETE_A = Copy B to A. Get the next B.
  146. * ACTION_DELETE_A_B = Get the next B.
  147. *
  148. * @param int $command
  149. * @throws JSMin_UnterminatedRegExpException|JSMin_UnterminatedStringException
  150. */
  151. protected function action($command)
  152. {
  153. if ($command === self::ACTION_DELETE_A_B
  154. && $this->b === ' '
  155. && ($this->a === '+' || $this->a === '-')) {
  156. // Note: we're at an addition/substraction operator; the inputIndex
  157. // will certainly be a valid index
  158. if ($this->input[$this->inputIndex] === $this->a) {
  159. // This is "+ +" or "- -". Don't delete the space.
  160. $command = self::ACTION_KEEP_A;
  161. }
  162. }
  163. switch ($command) {
  164. case self::ACTION_KEEP_A:
  165. $this->output .= $this->a;
  166. $this->lastByteOut = $this->a;
  167. // fallthrough
  168. case self::ACTION_DELETE_A:
  169. $this->a = $this->b;
  170. if ($this->a === "'" || $this->a === '"') { // string literal
  171. $str = $this->a; // in case needed for exception
  172. while (true) {
  173. $this->output .= $this->a;
  174. $this->lastByteOut = $this->a;
  175. $this->a = $this->get();
  176. if ($this->a === $this->b) { // end quote
  177. break;
  178. }
  179. if (ord($this->a) <= self::ORD_LF) {
  180. throw new JSMin_UnterminatedStringException(
  181. "JSMin: Unterminated String at byte "
  182. . $this->inputIndex . ": {$str}");
  183. }
  184. $str .= $this->a;
  185. if ($this->a === '\\') {
  186. $this->output .= $this->a;
  187. $this->lastByteOut = $this->a;
  188. $this->a = $this->get();
  189. $str .= $this->a;
  190. }
  191. }
  192. }
  193. // fallthrough
  194. case self::ACTION_DELETE_A_B:
  195. $this->b = $this->next();
  196. if ($this->b === '/' && $this->isRegexpLiteral()) { // RegExp literal
  197. $this->output .= $this->a . $this->b;
  198. $pattern = '/'; // in case needed for exception
  199. while (true) {
  200. $this->a = $this->get();
  201. $pattern .= $this->a;
  202. if ($this->a === '/') { // end pattern
  203. break; // while (true)
  204. } elseif ($this->a === '\\') {
  205. $this->output .= $this->a;
  206. $this->a = $this->get();
  207. $pattern .= $this->a;
  208. } elseif (ord($this->a) <= self::ORD_LF) {
  209. throw new JSMin_UnterminatedRegExpException(
  210. "JSMin: Unterminated RegExp at byte "
  211. . $this->inputIndex .": {$pattern}");
  212. }
  213. $this->output .= $this->a;
  214. $this->lastByteOut = $this->a;
  215. }
  216. $this->b = $this->next();
  217. }
  218. // end case ACTION_DELETE_A_B
  219. }
  220. }
  221. /**
  222. * @return bool
  223. */
  224. protected function isRegexpLiteral()
  225. {
  226. if (false !== strpos("\n{;(,=:[!&|?", $this->a)) { // we aren't dividing
  227. return true;
  228. }
  229. if (' ' === $this->a) {
  230. $length = strlen($this->output);
  231. if ($length < 2) { // weird edge case
  232. return true;
  233. }
  234. // you can't divide a keyword
  235. if (preg_match('/(?:case|else|in|return|typeof)$/', $this->output, $m)) {
  236. if ($this->output === $m[0]) { // odd but could happen
  237. return true;
  238. }
  239. // make sure it's a keyword, not end of an identifier
  240. $charBeforeKeyword = substr($this->output, $length - strlen($m[0]) - 1, 1);
  241. if (! $this->isAlphaNum($charBeforeKeyword)) {
  242. return true;
  243. }
  244. }
  245. }
  246. return false;
  247. }
  248. /**
  249. * Get next char. Convert ctrl char to space.
  250. *
  251. * @return string
  252. */
  253. protected function get()
  254. {
  255. $c = $this->lookAhead;
  256. $this->lookAhead = null;
  257. if ($c === null) {
  258. if ($this->inputIndex < $this->inputLength) {
  259. $c = $this->input[$this->inputIndex];
  260. $this->inputIndex += 1;
  261. } else {
  262. return null;
  263. }
  264. }
  265. if ($c === "\r" || $c === "\n") {
  266. return "\n";
  267. }
  268. if (ord($c) < self::ORD_SPACE) { // control char
  269. return ' ';
  270. }
  271. return $c;
  272. }
  273. /**
  274. * Get next char. If is ctrl character, translate to a space or newline.
  275. *
  276. * @return string
  277. */
  278. protected function peek()
  279. {
  280. $this->lookAhead = $this->get();
  281. return $this->lookAhead;
  282. }
  283. /**
  284. * Is $c a letter, digit, underscore, dollar sign, escape, or non-ASCII?
  285. *
  286. * @param string $c
  287. *
  288. * @return bool
  289. */
  290. protected function isAlphaNum($c)
  291. {
  292. return (preg_match('/^[0-9a-zA-Z_\\$\\\\]$/', $c) || ord($c) > 126);
  293. }
  294. /**
  295. * @return string
  296. */
  297. protected function singleLineComment()
  298. {
  299. $comment = '';
  300. while (true) {
  301. $get = $this->get();
  302. $comment .= $get;
  303. if (ord($get) <= self::ORD_LF) { // EOL reached
  304. // if IE conditional comment
  305. if (preg_match('/^\\/@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
  306. return "/{$comment}";
  307. }
  308. return $get;
  309. }
  310. }
  311. }
  312. /**
  313. * @return string
  314. * @throws JSMin_UnterminatedCommentException
  315. */
  316. protected function multipleLineComment()
  317. {
  318. $this->get();
  319. $comment = '';
  320. while (true) {
  321. $get = $this->get();
  322. if ($get === '*') {
  323. if ($this->peek() === '/') { // end of comment reached
  324. $this->get();
  325. // if comment preserved by YUI Compressor
  326. if (0 === strpos($comment, '!')) {
  327. return "\n/*!" . substr($comment, 1) . "*/\n";
  328. }
  329. // if IE conditional comment
  330. if (preg_match('/^@(?:cc_on|if|elif|else|end)\\b/', $comment)) {
  331. return "/*{$comment}*/";
  332. }
  333. return ' ';
  334. }
  335. } elseif ($get === null) {
  336. throw new JSMin_UnterminatedCommentException(
  337. "JSMin: Unterminated comment at byte "
  338. . $this->inputIndex . ": /*{$comment}");
  339. }
  340. $comment .= $get;
  341. }
  342. }
  343. /**
  344. * Get the next character, skipping over comments.
  345. * Some comments may be preserved.
  346. *
  347. * @return string
  348. */
  349. protected function next()
  350. {
  351. $get = $this->get();
  352. if ($get !== '/') {
  353. return $get;
  354. }
  355. switch ($this->peek()) {
  356. case '/': return $this->singleLineComment();
  357. case '*': return $this->multipleLineComment();
  358. default: return $get;
  359. }
  360. }
  361. }
  362. class JSMin_UnterminatedStringException extends Exception {}
  363. class JSMin_UnterminatedCommentException extends Exception {}
  364. class JSMin_UnterminatedRegExpException extends Exception {}