PageRenderTime 45ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/jssource/Minifier.php

https://gitlab.com/tjaafar/SuiteCRM
PHP | 459 lines | 251 code | 61 blank | 147 comment | 48 complexity | 715c5d44e0fc304857e1f466fc20533e MD5 | raw file
  1. <?php
  2. /**
  3. * JShrink
  4. *
  5. * Copyright (c) 2009-2012, Robert Hafner <tedivm@tedivm.com>.
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * * Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * * Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * * Neither the name of Robert Hafner nor the names of his
  21. * contributors may be used to endorse or promote products derived
  22. * from this software without specific prior written permission.
  23. *
  24. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  27. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  30. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  33. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  34. * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  35. * POSSIBILITY OF SUCH DAMAGE.
  36. *
  37. * @package JShrink
  38. * @author Robert Hafner <tedivm@tedivm.com>
  39. * @copyright 2009-2012 Robert Hafner <tedivm@tedivm.com>
  40. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  41. * @link https://github.com/tedivm/JShrink
  42. * @version Release: 0.4
  43. */
  44. // Some changes done by Akshay Joshi to preserve compatibility with PHP 5.2.
  45. /**
  46. * Minifier
  47. *
  48. * Usage - Minifier::minify($js);
  49. * Usage - Minifier::minify($js, $options);
  50. * Usage - Minifier::minify($js, array('flaggedComments' => false));
  51. *
  52. * @version 0.4
  53. * @package JShrink
  54. * @author Robert Hafner <tedivm@tedivm.com>
  55. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  56. */
  57. class Minifier
  58. {
  59. /**
  60. * The input javascript to be minified.
  61. *
  62. * @var string
  63. */
  64. protected $input;
  65. /**
  66. * The location of the character (in the input string) that is next to be processed.
  67. *
  68. * @var int
  69. */
  70. protected $index = 0;
  71. /**
  72. * The first of the characters currently being looked at.
  73. *
  74. * @var string
  75. */
  76. protected $a = '';
  77. /**
  78. * The next character being looked at (after a);
  79. *
  80. * @var string
  81. */
  82. protected $b = '';
  83. /**
  84. * This character is only active when certain look ahead actions take place.
  85. *
  86. * @var string
  87. */
  88. protected $c;
  89. /**
  90. * Contains the options for the current minification process.
  91. *
  92. * @var array
  93. */
  94. protected $options;
  95. /**
  96. * Contains the default options for minification. This array is merged with the one passed in by the user to create
  97. * the request specific set of options (stored in the $options attribute).
  98. *
  99. * @var array
  100. */
  101. static protected $defaultOptions = array('flaggedComments' => true);
  102. /**
  103. * Contains a copy of the JShrink object used to run minification. This is only used internally, and is only stored
  104. * for performance reasons. There is no internal data shared between minification requests.
  105. */
  106. static protected $jshrink;
  107. /**
  108. * Minifier::minify takes a string containing javascript and removes unneeded characters in order to shrink the code
  109. * without altering it's functionality.
  110. */
  111. static public function minify($js, $options = array())
  112. {
  113. try{
  114. ob_start();
  115. $currentOptions = array_merge(self::$defaultOptions, $options);
  116. if(!isset(self::$jshrink))
  117. self::$jshrink = new Minifier();
  118. self::$jshrink->breakdownScript($js, $currentOptions);
  119. return ob_get_clean();
  120. }catch(Exception $e){
  121. if(isset(self::$jshrink))
  122. self::$jshrink->clean();
  123. ob_end_clean();
  124. throw $e;
  125. }
  126. }
  127. /**
  128. * Processes a javascript string and outputs only the required characters, stripping out all unneeded characters.
  129. *
  130. * @param string $js The raw javascript to be minified
  131. * @param array $currentOptions Various runtime options in an associative array
  132. */
  133. protected function breakdownScript($js, $currentOptions)
  134. {
  135. // reset work attributes in case this isn't the first run.
  136. $this->clean();
  137. $this->options = $currentOptions;
  138. $js = str_replace("\r\n", "\n", $js);
  139. $this->input = str_replace("\r", "\n", $js);
  140. $this->input = preg_replace('/\h/u', ' ', $this->input);
  141. $this->a = $this->getReal();
  142. // the only time the length can be higher than 1 is if a conditional comment needs to be displayed
  143. // and the only time that can happen for $a is on the very first run
  144. while(strlen($this->a) > 1)
  145. {
  146. echo $this->a;
  147. $this->a = $this->getReal();
  148. }
  149. $this->b = $this->getReal();
  150. while($this->a !== false && !is_null($this->a) && $this->a !== '')
  151. {
  152. // now we give $b the same check for conditional comments we gave $a before we began looping
  153. if(strlen($this->b) > 1)
  154. {
  155. echo $this->a . $this->b;
  156. $this->a = $this->getReal();
  157. $this->b = $this->getReal();
  158. continue;
  159. }
  160. switch($this->a)
  161. {
  162. // new lines
  163. case "\n":
  164. // if the next line is something that can't stand alone preserve the newline
  165. if($this->b != '' && strpos('(-+{[@', $this->b) !== false)
  166. {
  167. echo $this->a;
  168. $this->saveString();
  169. break;
  170. }
  171. // if its a space we move down to the string test below
  172. if($this->b === ' ')
  173. break;
  174. // otherwise we treat the newline like a space
  175. case ' ':
  176. if(self::isAlphaNumeric($this->b))
  177. echo $this->a;
  178. $this->saveString();
  179. break;
  180. default:
  181. switch($this->b)
  182. {
  183. case "\n":
  184. if(strpos('}])+-"\'', $this->a) !== false)
  185. {
  186. echo $this->a;
  187. $this->saveString();
  188. break;
  189. }else{
  190. if(self::isAlphaNumeric($this->a))
  191. {
  192. echo $this->a;
  193. $this->saveString();
  194. }
  195. }
  196. break;
  197. case ' ':
  198. if(!self::isAlphaNumeric($this->a))
  199. break;
  200. default:
  201. // check for some regex that breaks stuff
  202. if($this->a == '/' && ($this->b == '\'' || $this->b == '"'))
  203. {
  204. $this->saveRegex();
  205. continue;
  206. }
  207. echo $this->a;
  208. $this->saveString();
  209. break;
  210. }
  211. }
  212. // do reg check of doom
  213. $this->b = $this->getReal();
  214. if(($this->b == '/' && strpos('(,=:[!&|?', $this->a) !== false))
  215. $this->saveRegex();
  216. }
  217. $this->clean();
  218. }
  219. /**
  220. * Returns the next string for processing based off of the current index.
  221. *
  222. * @return string
  223. */
  224. protected function getChar()
  225. {
  226. if(isset($this->c))
  227. {
  228. $char = $this->c;
  229. unset($this->c);
  230. }else{
  231. $tchar = substr($this->input, $this->index, 1);
  232. if(isset($tchar) && $tchar !== false)
  233. {
  234. $char = $tchar;
  235. $this->index++;
  236. }else{
  237. return false;
  238. }
  239. }
  240. if($char !== "\n" && ord($char) < 32)
  241. return ' ';
  242. return $char;
  243. }
  244. /**
  245. * This function gets the next "real" character. It is essentially a wrapper around the getChar function that skips
  246. * comments. This has signifigant peformance benefits as the skipping is done using native functions (ie, c code)
  247. * rather than in script php.
  248. *
  249. * @return string Next 'real' character to be processed.
  250. */
  251. protected function getReal()
  252. {
  253. $startIndex = $this->index;
  254. $char = $this->getChar();
  255. if($char == '/')
  256. {
  257. $this->c = $this->getChar();
  258. if($this->c == '/')
  259. {
  260. $thirdCommentString = substr($this->input, $this->index, 1);
  261. // kill rest of line
  262. $char = $this->getNext("\n");
  263. if($thirdCommentString == '@')
  264. {
  265. $endPoint = ($this->index) - $startIndex;
  266. unset($this->c);
  267. $char = "\n" . substr($this->input, $startIndex, $endPoint);// . "\n";
  268. }else{
  269. $char = $this->getChar();
  270. $char = $this->getChar();
  271. }
  272. }elseif($this->c == '*'){
  273. $this->getChar(); // current C
  274. $thirdCommentString = $this->getChar();
  275. if($thirdCommentString == '@')
  276. {
  277. // conditional comment
  278. // we're gonna back up a bit and and send the comment back, where the first
  279. // char will be echoed and the rest will be treated like a string
  280. $this->index = $this->index-2;
  281. return '/';
  282. }elseif($this->getNext('*/')){
  283. // kill everything up to the next */
  284. $this->getChar(); // get *
  285. $this->getChar(); // get /
  286. $char = $this->getChar(); // get next real character
  287. // if YUI-style comments are enabled we reinsert it into the stream
  288. if($this->options['flaggedComments'] && $thirdCommentString == '!')
  289. {
  290. $endPoint = ($this->index - 1) - $startIndex;
  291. echo "\n" . substr($this->input, $startIndex, $endPoint) . "\n";
  292. }
  293. }else{
  294. $char = false;
  295. }
  296. if($char === false)
  297. throw new RuntimeException('Stray comment. ' . $this->index);
  298. // if we're here c is part of the comment and therefore tossed
  299. if(isset($this->c))
  300. unset($this->c);
  301. }
  302. }
  303. return $char;
  304. }
  305. /**
  306. * Pushes the index ahead to the next instance of the supplied string. If it is found the first character of the
  307. * string is returned.
  308. *
  309. * @return string|false Returns the first character of the string if found, false otherwise.
  310. */
  311. protected function getNext($string)
  312. {
  313. $pos = strpos($this->input, $string, $this->index);
  314. if($pos === false)
  315. return false;
  316. $this->index = $pos;
  317. return substr($this->input, $this->index, 1);
  318. }
  319. /**
  320. * When a javascript string is detected this function crawls for the end of it and saves the whole string.
  321. *
  322. */
  323. protected function saveString()
  324. {
  325. $this->a = $this->b;
  326. if($this->a == "'" || $this->a == '"') // is the character a quote
  327. {
  328. // save literal string
  329. $stringType = $this->a;
  330. while(1)
  331. {
  332. echo $this->a;
  333. $this->a = $this->getChar();
  334. switch($this->a)
  335. {
  336. case $stringType:
  337. break 2;
  338. case "\n":
  339. throw new RuntimeException('Unclosed string. ' . $this->index);
  340. break;
  341. case '\\':
  342. echo $this->a;
  343. $this->a = $this->getChar();
  344. }
  345. }
  346. }
  347. }
  348. /**
  349. * When a regular expression is detected this funcion crawls for the end of it and saves the whole regex.
  350. */
  351. protected function saveRegex()
  352. {
  353. echo $this->a . $this->b;
  354. while(($this->a = $this->getChar()) !== false)
  355. {
  356. if($this->a == '/')
  357. break;
  358. if($this->a == '\\')
  359. {
  360. echo $this->a;
  361. $this->a = $this->getChar();
  362. }
  363. if($this->a == "\n")
  364. throw new RuntimeException('Stray regex pattern. ' . $this->index);
  365. echo $this->a;
  366. }
  367. $this->b = $this->getReal();
  368. }
  369. /**
  370. * Resets attributes that do not need to be stored between requests so that the next request is ready to go.
  371. */
  372. protected function clean()
  373. {
  374. unset($this->input);
  375. $this->index = 0;
  376. $this->a = $this->b = '';
  377. unset($this->c);
  378. unset($this->options);
  379. }
  380. /**
  381. * Checks to see if a character is alphanumeric.
  382. *
  383. * @return bool
  384. */
  385. static protected function isAlphaNumeric($char)
  386. {
  387. return preg_match('/^[\w\$]$/', $char) === 1 || $char == '/';
  388. }
  389. }