5 * Copyright (c) 2009-2012, Robert Hafner <tedivm@tedivm.com>.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * * Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
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
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.
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.
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
45 // Some changes done by Akshay Joshi to preserve compatibility with PHP 5.2.
50 * Usage - Minifier::minify($js);
51 * Usage - Minifier::minify($js, $options);
52 * Usage - Minifier::minify($js, array('flaggedComments' => false));
56 * @author Robert Hafner <tedivm@tedivm.com>
57 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
62 * The input javascript to be minified.
69 * The location of the character (in the input string) that is next to be processed.
76 * The first of the characters currently being looked at.
84 * The next character being looked at (after a);
91 * This character is only active when certain look ahead actions take place.
98 * Contains the options for the current minification process.
105 * Contains the default options for minification. This array is merged with the one passed in by the user to create
106 * the request specific set of options (stored in the $options attribute).
110 static protected $defaultOptions = array('flaggedComments' => true);
113 * Contains a copy of the JShrink object used to run minification. This is only used internally, and is only stored
114 * for performance reasons. There is no internal data shared between minification requests.
116 static protected $jshrink;
119 * Minifier::minify takes a string containing javascript and removes unneeded characters in order to shrink the code
120 * without altering it's functionality.
122 static public function minify($js, $options = array())
126 $currentOptions = array_merge(self::$defaultOptions, $options);
128 if(!isset(self::$jshrink))
129 self::$jshrink = new Minifier();
131 self::$jshrink->breakdownScript($js, $currentOptions);
132 return ob_get_clean();
134 }catch(Exception $e){
135 if(isset(self::$jshrink))
136 self::$jshrink->clean();
144 * Processes a javascript string and outputs only the required characters, stripping out all unneeded characters.
146 * @param string $js The raw javascript to be minified
147 * @param array $currentOptions Various runtime options in an associative array
149 protected function breakdownScript($js, $currentOptions)
151 // reset work attributes in case this isn't the first run.
154 $this->options = $currentOptions;
156 $js = str_replace("\r\n", "\n", $js);
157 $this->input = str_replace("\r", "\n", $js);
158 $this->input = preg_replace('/\h/u', ' ', $this->input);
161 $this->a = $this->getReal();
163 // the only time the length can be higher than 1 is if a conditional comment needs to be displayed
164 // and the only time that can happen for $a is on the very first run
165 while(strlen($this->a) > 1)
168 $this->a = $this->getReal();
171 $this->b = $this->getReal();
173 while($this->a !== false && !is_null($this->a) && $this->a !== '')
176 // now we give $b the same check for conditional comments we gave $a before we began looping
177 if(strlen($this->b) > 1)
179 echo $this->a . $this->b;
180 $this->a = $this->getReal();
181 $this->b = $this->getReal();
189 // if the next line is something that can't stand alone preserve the newline
190 if($this->b != '' && strpos('(-+{[@', $this->b) !== false)
197 // if its a space we move down to the string test below
201 // otherwise we treat the newline like a space
204 if(self::isAlphaNumeric($this->b))
214 if(strpos('}])+-"\'', $this->a) !== false)
220 if(self::isAlphaNumeric($this->a))
229 if(!self::isAlphaNumeric($this->a))
233 // check for some regex that breaks stuff
234 if($this->a == '/' && ($this->b == '\'' || $this->b == '"'))
246 // do reg check of doom
247 $this->b = $this->getReal();
249 if(($this->b == '/' && strpos('(,=:[!&|?', $this->a) !== false))
256 * Returns the next string for processing based off of the current index.
260 protected function getChar()
267 $tchar = substr($this->input, $this->index, 1);
268 if(isset($tchar) && $tchar !== false)
277 if($char !== "\n" && ord($char) < 32)
284 * This function gets the next "real" character. It is essentially a wrapper around the getChar function that skips
285 * comments. This has signifigant peformance benefits as the skipping is done using native functions (ie, c code)
286 * rather than in script php.
288 * @return string Next 'real' character to be processed.
290 protected function getReal()
292 $startIndex = $this->index;
293 $char = $this->getChar();
297 $this->c = $this->getChar();
301 $thirdCommentString = substr($this->input, $this->index, 1);
304 $char = $this->getNext("\n");
306 if($thirdCommentString == '@')
308 $endPoint = ($this->index) - $startIndex;
310 $char = "\n" . substr($this->input, $startIndex, $endPoint);// . "\n";
312 $char = $this->getChar();
313 $char = $this->getChar();
316 }elseif($this->c == '*'){
318 $this->getChar(); // current C
319 $thirdCommentString = $this->getChar();
321 if($thirdCommentString == '@')
323 // conditional comment
325 // we're gonna back up a bit and and send the comment back, where the first
326 // char will be echoed and the rest will be treated like a string
327 $this->index = $this->index-2;
330 }elseif($this->getNext('*/')){
331 // kill everything up to the next */
333 $this->getChar(); // get *
334 $this->getChar(); // get /
336 $char = $this->getChar(); // get next real character
338 // if YUI-style comments are enabled we reinsert it into the stream
339 if($this->options['flaggedComments'] && $thirdCommentString == '!')
341 $endPoint = ($this->index - 1) - $startIndex;
342 echo "\n" . substr($this->input, $startIndex, $endPoint) . "\n";
350 throw new RuntimeException('Stray comment. ' . $this->index);
352 // if we're here c is part of the comment and therefore tossed
361 * Pushes the index ahead to the next instance of the supplied string. If it is found the first character of the
362 * string is returned.
364 * @return string|false Returns the first character of the string if found, false otherwise.
366 protected function getNext($string)
368 $pos = strpos($this->input, $string, $this->index);
374 return substr($this->input, $this->index, 1);
378 * When a javascript string is detected this function crawls for the end of it and saves the whole string.
381 protected function saveString()
384 if($this->a == "'" || $this->a == '"') // is the character a quote
386 // save literal string
387 $stringType = $this->a;
392 $this->a = $this->getChar();
400 throw new RuntimeException('Unclosed string. ' . $this->index);
405 $this->a = $this->getChar();
412 * When a regular expression is detected this funcion crawls for the end of it and saves the whole regex.
414 protected function saveRegex()
416 echo $this->a . $this->b;
418 while(($this->a = $this->getChar()) !== false)
426 $this->a = $this->getChar();
430 throw new RuntimeException('Stray regex pattern. ' . $this->index);
434 $this->b = $this->getReal();
438 * Resets attributes that do not need to be stored between requests so that the next request is ready to go.
440 protected function clean()
444 $this->a = $this->b = '';
446 unset($this->options);
450 * Checks to see if a character is alphanumeric.
454 static protected function isAlphaNumeric($char)
456 return preg_match('/^[\w\$]$/', $char) === 1 || $char == '/';