4 * cssmin.php rev ebaf67b 12/06/2013
5 * Author: Tubal Martin - http://tubalmartin.me/
6 * Repo: https://github.com/tubalmartin/YUI-CSS-compressor-PHP-port
8 * This is a PHP port of the CSS minification tool distributed with YUICompressor,
9 * itself a port of the cssmin utility by Isaac Schlueter - http://foohack.com/
10 * Permission is hereby granted to use the PHP version under the same
11 * conditions as the YUICompressor.
16 * http://developer.yahoo.com/yui/compressor/
17 * Author: Julien Lecomte - http://www.julienlecomte.net/
18 * Copyright (c) 2013 Yahoo! Inc. All rights reserved.
19 * The copyrights embodied in the content of this file are licensed
20 * by Yahoo! Inc. under the BSD (revised) open source license.
25 const NL = '___YUICSSMIN_PRESERVED_NL___';
26 const TOKEN = '___YUICSSMIN_PRESERVED_TOKEN_';
27 const COMMENT = '___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_';
28 const CLASSCOLON = '___YUICSSMIN_PSEUDOCLASSCOLON___';
29 const QUERY_FRACTION = '___YUICSSMIN_QUERY_FRACTION___';
32 private $preserved_tokens;
33 private $memory_limit;
34 private $max_execution_time;
35 private $pcre_backtrack_limit;
36 private $pcre_recursion_limit;
37 private $raise_php_limits;
40 * @param bool|int $raise_php_limits
41 * If true, PHP settings will be raised if needed
43 public function __construct($raise_php_limits = TRUE)
45 // Set suggested PHP limits
46 $this->memory_limit = 128 * 1048576; // 128MB in bytes
47 $this->max_execution_time = 60; // 1 min
48 $this->pcre_backtrack_limit = 1000 * 1000;
49 $this->pcre_recursion_limit = 500 * 1000;
51 $this->raise_php_limits = (bool) $raise_php_limits;
55 * Minify a string of CSS
57 * @param int|bool $linebreak_pos
60 public function run($css = '', $linebreak_pos = FALSE)
66 if ($this->raise_php_limits) {
67 $this->do_raise_php_limits();
70 $this->comments = array();
71 $this->preserved_tokens = array();
74 $length = strlen($css);
76 $css = $this->extract_data_urls($css);
78 // collect all comment blocks...
79 while (($start_index = $this->index_of($css, '/*', $start_index)) >= 0) {
80 $end_index = $this->index_of($css, '*/', $start_index + 2);
84 $comment_found = $this->str_slice($css, $start_index + 2, $end_index);
85 $this->comments[] = $comment_found;
86 $comment_preserve_string = self::COMMENT . (count($this->comments) - 1) . '___';
87 $css = $this->str_slice($css, 0, $start_index + 2) . $comment_preserve_string . $this->str_slice($css, $end_index);
88 // Set correct start_index: Fixes issue #2528130
89 $start_index = $end_index + 2 + strlen($comment_preserve_string) - strlen($comment_found);
92 // preserve strings so their content doesn't get accidentally minified
93 $css = preg_replace_callback('/(?:"(?:[^\\\\"]|\\\\.|\\\\)*")|'."(?:'(?:[^\\\\']|\\\\.|\\\\)*')/S", array($this, 'replace_string'), $css);
95 // Let's divide css code in chunks of 25.000 chars aprox.
96 // Reason: PHP's PCRE functions like preg_replace have a "backtrack limit"
97 // of 100.000 chars by default (php < 5.3.7) so if we're dealing with really
98 // long strings and a (sub)pattern matches a number of chars greater than
99 // the backtrack limit number (i.e. /(.*)/s) PCRE functions may fail silently
100 // returning NULL and $css would be empty.
102 $charset_regexp = '/(@charset)( [^;]+;)/i';
103 $css_chunks = array();
104 $css_chunk_length = 25000; // aprox size, not exact
106 $i = $css_chunk_length; // save initial iterations
110 // if the number of characters is 25000 or less, do not chunk
111 if ($l <= $css_chunk_length) {
112 $css_chunks[] = $css;
114 // chunk css code securely
116 $i += 50; // save iterations. 500 checks for a closing curly brace }
117 if ($l - $start_index <= $css_chunk_length || $i >= $l) {
118 $css_chunks[] = $this->str_slice($css, $start_index);
121 if ($css[$i - 1] === '}' && $i - $start_index > $css_chunk_length) {
122 // If there are two ending curly braces }} separated or not by spaces,
123 // join them in the same chunk (i.e. @media blocks)
124 $next_chunk = substr($css, $i);
125 if (preg_match('/^\s*\}/', $next_chunk)) {
126 $i = $i + $this->index_of($next_chunk, '}') + 1;
129 $css_chunks[] = $this->str_slice($css, $start_index, $i);
136 for ($i = 0, $n = count($css_chunks); $i < $n; $i++) {
137 $css_chunks[$i] = $this->minify($css_chunks[$i], $linebreak_pos);
138 // Keep the first @charset at-rule found
139 if (empty($charset) && preg_match($charset_regexp, $css_chunks[$i], $matches)) {
140 $charset = strtolower($matches[1]) . $matches[2];
142 // Delete all @charset at-rules
143 $css_chunks[$i] = preg_replace($charset_regexp, '', $css_chunks[$i]);
146 // Update the first chunk and push the charset to the top of the file.
147 $css_chunks[0] = $charset . $css_chunks[0];
149 return implode('', $css_chunks);
153 * Sets the memory limit for this script
154 * @param int|string $limit
156 public function set_memory_limit($limit)
158 $this->memory_limit = $this->normalize_int($limit);
162 * Sets the maximum execution time for this script
163 * @param int|string $seconds
165 public function set_max_execution_time($seconds)
167 $this->max_execution_time = (int) $seconds;
171 * Sets the PCRE backtrack limit for this script
174 public function set_pcre_backtrack_limit($limit)
176 $this->pcre_backtrack_limit = (int) $limit;
180 * Sets the PCRE recursion limit for this script
183 public function set_pcre_recursion_limit($limit)
185 $this->pcre_recursion_limit = (int) $limit;
189 * Try to configure PHP to use at least the suggested minimum settings
191 private function do_raise_php_limits()
194 'memory_limit' => $this->memory_limit,
195 'max_execution_time' => $this->max_execution_time,
196 'pcre.backtrack_limit' => $this->pcre_backtrack_limit,
197 'pcre.recursion_limit' => $this->pcre_recursion_limit
200 // If current settings are higher respect them.
201 foreach ($php_limits as $name => $suggested) {
202 $current = $this->normalize_int(ini_get($name));
203 // memory_limit exception: allow -1 for "no memory limit".
204 if ($current > -1 && ($suggested == -1 || $current < $suggested)) {
205 ini_set($name, $suggested);
211 * Does bulk of the minification
213 * @param int|bool $linebreak_pos
216 private function minify($css, $linebreak_pos)
218 // strings are safe, now wrestle the comments
219 for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
221 $token = $this->comments[$i];
222 $placeholder = '/' . self::COMMENT . $i . '___/';
224 // ! in the first position of the comment means preserve
225 // so push to the preserved tokens keeping the !
226 if (substr($token, 0, 1) === '!') {
227 $this->preserved_tokens[] = $token;
228 $token_tring = self::TOKEN . (count($this->preserved_tokens) - 1) . '___';
229 $css = preg_replace($placeholder, $token_tring, $css, 1);
230 // Preserve new lines for /*! important comments
231 $css = preg_replace('/\s*[\n\r\f]+\s*(\/\*'. $token_tring .')/S', self::NL.'$1', $css);
232 $css = preg_replace('/('. $token_tring .'\*\/)\s*[\n\r\f]+\s*/', '$1'.self::NL, $css);
236 // \ in the last position looks like hack for Mac/IE5
237 // shorten that to /*\*/ and the next one to /**/
238 if (substr($token, (strlen($token) - 1), 1) === '\\') {
239 $this->preserved_tokens[] = '\\';
240 $css = preg_replace($placeholder, self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
241 $i = $i + 1; // attn: advancing the loop
242 $this->preserved_tokens[] = '';
243 $css = preg_replace('/' . self::COMMENT . $i . '___/', self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
247 // keep empty comments after child selectors (IE7 hack)
248 // e.g. html >/**/ body
249 if (strlen($token) === 0) {
250 $start_index = $this->index_of($css, $this->str_slice($placeholder, 1, -1));
251 if ($start_index > 2) {
252 if (substr($css, $start_index - 3, 1) === '>') {
253 $this->preserved_tokens[] = '';
254 $css = preg_replace($placeholder, self::TOKEN . (count($this->preserved_tokens) - 1) . '___', $css, 1);
259 // in all other cases kill the comment
260 $css = preg_replace('/\/\*' . $this->str_slice($placeholder, 1, -1) . '\*\//', '', $css, 1);
264 // Normalize all whitespace strings to single spaces. Easier to work with that way.
265 $css = preg_replace('/\s+/', ' ', $css);
267 // Shorten & preserve calculations calc(...) since spaces are important
268 $css = preg_replace_callback('/calc(\(((?:[^\(\)]+|(?1))*)\))/i', array($this, 'replace_calc'), $css);
270 // Replace positive sign from numbers preceded by : or a white-space before the leading space is removed
271 // +1.2em to 1.2em, +.8px to .8px, +2% to 2%
272 $css = preg_replace('/((?<!\\\\)\:|\s)\+(\.?\d+)/S', '$1$2', $css);
274 // Remove leading zeros from integer and float numbers preceded by : or a white-space
275 // 000.6 to .6, -0.8 to -.8, 0050 to 50, -01.05 to -1.05
276 $css = preg_replace('/((?<!\\\\)\:|\s)(\-?)0+(\.?\d+)/S', '$1$2$3', $css);
278 // Remove trailing zeros from float numbers preceded by : or a white-space
279 // -6.0100em to -6.01em, .0100 to .01, 1.200px to 1.2px
280 $css = preg_replace('/((?<!\\\\)\:|\s)(\-?)(\d?\.\d+?)0+([^\d])/S', '$1$2$3$4', $css);
282 // Remove trailing .0 -> -9.0 to -9
283 $css = preg_replace('/((?<!\\\\)\:|\s)(\-?\d+)\.0([^\d])/S', '$1$2$3', $css);
285 // Replace 0 length numbers with 0
286 $css = preg_replace('/((?<!\\\\)\:|\s)\-?\.?0+([^\d])/S', '${1}0$2', $css);
288 // Remove the spaces before the things that should not have spaces before them.
289 // But, be careful not to turn "p :link {...}" into "p:link{...}"
290 // Swap out any pseudo-class colons with the token, and then swap back.
291 $css = preg_replace_callback('/(?:^|\})(?:(?:[^\{\:])+\:)+(?:[^\{]*\{)/', array($this, 'replace_colon'), $css);
293 // Remove spaces before the things that should not have spaces before them.
294 $css = preg_replace('/\s+([\!\{\}\;\:\>\+\(\)\]\~\=,])/', '$1', $css);
296 // Restore spaces for !important
297 $css = preg_replace('/\!important/i', ' !important', $css);
299 // bring back the colon
300 $css = preg_replace('/' . self::CLASSCOLON . '/', ':', $css);
302 // retain space for special IE6 cases
303 $css = preg_replace_callback('/\:first\-(line|letter)(\{|,)/i', array($this, 'lowercase_pseudo_first'), $css);
305 // no space after the end of a preserved comment
306 $css = preg_replace('/\*\/ /', '*/', $css);
308 // lowercase some popular @directives
309 $css = preg_replace_callback('/@(font-face|import|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?keyframe|media|page|namespace)/i', array($this, 'lowercase_directives'), $css);
311 // lowercase some more common pseudo-elements
312 $css = preg_replace_callback('/:(active|after|before|checked|disabled|empty|enabled|first-(?:child|of-type)|focus|hover|last-(?:child|of-type)|link|only-(?:child|of-type)|root|:selection|target|visited)/i', array($this, 'lowercase_pseudo_elements'), $css);
314 // lowercase some more common functions
315 $css = preg_replace_callback('/:(lang|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|(?:-(?:moz|webkit)-)?any)\(/i', array($this, 'lowercase_common_functions'), $css);
317 // lower case some common function that can be values
318 // NOTE: rgb() isn't useful as we replace with #hex later, as well as and() is already done for us
319 $css = preg_replace_callback('/([:,\( ]\s*)(attr|color-stop|from|rgba|to|url|(?:-(?:atsc|khtml|moz|ms|o|wap|webkit)-)?(?:calc|max|min|(?:repeating-)?(?:linear|radial)-gradient)|-webkit-gradient)/iS', array($this, 'lowercase_common_functions_values'), $css);
321 // Put the space back in some cases, to support stuff like
322 // @media screen and (-webkit-min-device-pixel-ratio:0){
323 $css = preg_replace('/\band\(/i', 'and (', $css);
325 // Remove the spaces after the things that should not have spaces after them.
326 $css = preg_replace('/([\!\{\}\:;\>\+\(\[\~\=,])\s+/S', '$1', $css);
328 // remove unnecessary semicolons
329 $css = preg_replace('/;+\}/', '}', $css);
331 // Fix for issue: #2528146
332 // Restore semicolon if the last property is prefixed with a `*` (lte IE7 hack)
333 // to avoid issues on Symbian S60 3.x browsers.
334 $css = preg_replace('/(\*[a-z0-9\-]+\s*\:[^;\}]+)(\})/', '$1;$2', $css);
336 // Replace 0 length units 0(px,em,%) with 0.
337 $css = preg_replace('/(^|[^0-9])(?:0?\.)?0(?:em|ex|ch|rem|vw|vh|vm|vmin|cm|mm|in|px|pt|pc|%|deg|g?rad|m?s|k?hz)/iS', '${1}0', $css);
339 // Replace 0 0; or 0 0 0; or 0 0 0 0; with 0.
340 $css = preg_replace('/\:0(?: 0){1,3}(;|\}| \!)/', ':0$1', $css);
342 // Fix for issue: #2528142
343 // Replace text-shadow:0; with text-shadow:0 0 0;
344 $css = preg_replace('/(text-shadow\:0)(;|\}| \!)/i', '$1 0 0$2', $css);
346 // Replace background-position:0; with background-position:0 0;
347 // same for transform-origin
348 // Changing -webkit-mask-position: 0 0 to just a single 0 will result in the second parameter defaulting to 50% (center)
349 $css = preg_replace('/(background\-position|webkit-mask-position|(?:webkit|moz|o|ms|)\-?transform\-origin)\:0(;|\}| \!)/iS', '$1:0 0$2', $css);
351 // Shorten colors from rgb(51,102,153) to #336699, rgb(100%,0%,0%) to #ff0000 (sRGB color space)
352 // Shorten colors from hsl(0, 100%, 50%) to #ff0000 (sRGB color space)
353 // This makes it more likely that it'll get further compressed in the next step.
354 $css = preg_replace_callback('/rgb\s*\(\s*([0-9,\s\-\.\%]+)\s*\)(.{1})/i', array($this, 'rgb_to_hex'), $css);
355 $css = preg_replace_callback('/hsl\s*\(\s*([0-9,\s\-\.\%]+)\s*\)(.{1})/i', array($this, 'hsl_to_hex'), $css);
357 // Shorten colors from #AABBCC to #ABC or short color name.
358 $css = $this->compress_hex_colors($css);
360 // border: none to border:0, outline: none to outline:0
361 $css = preg_replace('/(border\-?(?:top|right|bottom|left|)|outline)\:none(;|\}| \!)/iS', '$1:0$2', $css);
363 // shorter opacity IE filter
364 $css = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $css);
366 // Find a fraction that is used for Opera's -o-device-pixel-ratio query
367 // Add token to add the "\" back in later
368 $css = preg_replace('/\(([a-z\-]+):([0-9]+)\/([0-9]+)\)/i', '($1:$2'. self::QUERY_FRACTION .'$3)', $css);
370 // Remove empty rules.
371 $css = preg_replace('/[^\};\{\/]+\{\}/S', '', $css);
373 // Add "/" back to fix Opera -o-device-pixel-ratio query
374 $css = preg_replace('/'. self::QUERY_FRACTION .'/', '/', $css);
376 // Some source control tools don't like it when files containing lines longer
377 // than, say 8000 characters, are checked in. The linebreak option is used in
378 // that case to split long lines after a specific column.
379 if ($linebreak_pos !== FALSE && (int) $linebreak_pos >= 0) {
380 $linebreak_pos = (int) $linebreak_pos;
381 $start_index = $i = 0;
382 while ($i < strlen($css)) {
384 if ($css[$i - 1] === '}' && $i - $start_index > $linebreak_pos) {
385 $css = $this->str_slice($css, 0, $i) . "\n" . $this->str_slice($css, $i);
391 // Replace multiple semi-colons in a row by a single one
392 // See SF bug #1980989
393 $css = preg_replace('/;;+/', ';', $css);
395 // Restore new lines for /*! important comments
396 $css = preg_replace('/'. self::NL .'/', "\n", $css);
398 // Lowercase all uppercase properties
399 $css = preg_replace_callback('/(\{|\;)([A-Z\-]+)(\:)/', array($this, 'lowercase_properties'), $css);
401 // restore preserved comments and strings
402 for ($i = 0, $max = count($this->preserved_tokens); $i < $max; $i++) {
403 $css = preg_replace('/' . self::TOKEN . $i . '___/', $this->preserved_tokens[$i], $css, 1);
406 // Trim the final string (for any leading or trailing white spaces)
411 * Utility method to replace all data urls with tokens before we start
412 * compressing, to avoid performance issues running some of the subsequent
413 * regexes against large strings chunks.
418 private function extract_data_urls($css)
420 // Leave data urls alone to increase parse performance.
421 $max_index = strlen($css) - 1;
422 $append_index = $index = $last_index = $offset = 0;
424 $pattern = '/url\(\s*(["\']?)data\:/i';
426 // Since we need to account for non-base64 data urls, we need to handle
427 // ' and ) being part of the data string. Hence switching to indexOf,
428 // to determine whether or not we have matching string terminators and
429 // handling sb appends directly, instead of using matcher.append* methods.
431 while (preg_match($pattern, $css, $m, 0, $offset)) {
432 $index = $this->index_of($css, $m[0], $offset);
433 $last_index = $index + strlen($m[0]);
434 $start_index = $index + 4; // "url(".length()
435 $end_index = $last_index - 1;
436 $terminator = $m[1]; // ', " or empty (not quoted)
437 $found_terminator = FALSE;
439 if (strlen($terminator) === 0) {
443 while ($found_terminator === FALSE && $end_index+1 <= $max_index) {
444 $end_index = $this->index_of($css, $terminator, $end_index + 1);
446 // endIndex == 0 doesn't really apply here
447 if ($end_index > 0 && substr($css, $end_index - 1, 1) !== '\\') {
448 $found_terminator = TRUE;
449 if (')' != $terminator) {
450 $end_index = $this->index_of($css, ')', $end_index);
455 // Enough searching, start moving stuff over to the buffer
456 $sb[] = $this->str_slice($css, $append_index, $index);
458 if ($found_terminator) {
459 $token = $this->str_slice($css, $start_index, $end_index);
460 $token = preg_replace('/\s+/', '', $token);
461 $this->preserved_tokens[] = $token;
463 $preserver = 'url(' . self::TOKEN . (count($this->preserved_tokens) - 1) . '___)';
466 $append_index = $end_index + 1;
468 // No end terminator found, re-add the whole match. Should we throw/warn here?
469 $sb[] = $this->str_slice($css, $index, $last_index);
470 $append_index = $last_index;
473 $offset = $last_index;
476 $sb[] = $this->str_slice($css, $append_index);
478 return implode('', $sb);
482 * Utility method to compress hex color values of the form #AABBCC to #ABC or short color name.
484 * DOES NOT compress CSS ID selectors which match the above pattern (which would break things).
485 * e.g. #AddressForm { ... }
487 * DOES NOT compress IE filters, which have hex color values (which would break things).
488 * e.g. filter: chroma(color="#FFFFFF");
490 * DOES NOT compress invalid hex values.
491 * e.g. background-color: #aabbccdd
496 private function compress_hex_colors($css)
498 // Look for hex colors inside { ... } (to avoid IDs) and which don't have a =, or a " in front of them (to avoid filters)
499 $pattern = '/(\=\s*?["\']?)?#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])(\}|[^0-9a-f{][^{]*?\})/iS';
500 $_index = $index = $last_index = $offset = 0;
502 // See: http://ajaxmin.codeplex.com/wikipage?title=CSS%20Colors
505 '#008000' => 'green',
506 '#800000' => 'maroon',
508 '#808000' => 'olive',
509 '#ffa500' => 'orange',
510 '#800080' => 'purple',
511 '#c0c0c0' => 'silver',
516 while (preg_match($pattern, $css, $m, 0, $offset)) {
517 $index = $this->index_of($css, $m[0], $offset);
518 $last_index = $index + strlen($m[0]);
519 $is_filter = $m[1] !== null && $m[1] !== '';
521 $sb[] = $this->str_slice($css, $_index, $index);
524 // Restore, maintain case, otherwise filter will break
525 $sb[] = $m[1] . '#' . $m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7];
527 if (strtolower($m[2]) == strtolower($m[3]) &&
528 strtolower($m[4]) == strtolower($m[5]) &&
529 strtolower($m[6]) == strtolower($m[7])) {
531 $hex = '#' . strtolower($m[3] . $m[5] . $m[7]);
533 // Non compressible color, restore but lower case.
534 $hex = '#' . strtolower($m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7]);
536 // replace Hex colors to short safe color names
537 $sb[] = array_key_exists($hex, $short_safe) ? $short_safe[$hex] : $hex;
540 $_index = $offset = $last_index - strlen($m[8]);
543 $sb[] = $this->str_slice($css, $_index);
545 return implode('', $sb);
549 * ---------------------------------------------------------------------------------------------
552 private function replace_string($matches)
554 $match = $matches[0];
555 $quote = substr($match, 0, 1);
556 // Must use addcslashes in PHP to avoid parsing of backslashes
557 $match = addcslashes($this->str_slice($match, 1, -1), '\\');
559 // maybe the string contains a comment-like substring?
560 // one, maybe more? put'em back then
561 if (($pos = $this->index_of($match, self::COMMENT)) >= 0) {
562 for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
563 $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1);
567 // minify alpha opacity in filter strings
568 $match = preg_replace('/progid\:DXImageTransform\.Microsoft\.Alpha\(Opacity\=/i', 'alpha(opacity=', $match);
570 $this->preserved_tokens[] = $match;
571 return $quote . self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . $quote;
574 private function replace_colon($matches)
576 return preg_replace('/\:/', self::CLASSCOLON, $matches[0]);
579 private function replace_calc($matches)
581 $this->preserved_tokens[] = trim(preg_replace('/\s*([\*\/\(\),])\s*/', '$1', $matches[2]));
582 return 'calc('. self::TOKEN . (count($this->preserved_tokens) - 1) . '___' . ')';
585 private function rgb_to_hex($matches)
587 // Support for percentage values rgb(100%, 0%, 45%);
588 if ($this->index_of($matches[1], '%') >= 0){
589 $rgbcolors = explode(',', str_replace('%', '', $matches[1]));
590 for ($i = 0; $i < count($rgbcolors); $i++) {
591 $rgbcolors[$i] = $this->round_number(floatval($rgbcolors[$i]) * 2.55);
594 $rgbcolors = explode(',', $matches[1]);
597 // Values outside the sRGB color space should be clipped (0-255)
598 for ($i = 0; $i < count($rgbcolors); $i++) {
599 $rgbcolors[$i] = $this->clamp_number(intval($rgbcolors[$i], 10), 0, 255);
600 $rgbcolors[$i] = sprintf("%02x", $rgbcolors[$i]);
603 // Fix for issue #2528093
604 if (!preg_match('/[\s\,\);\}]/', $matches[2])){
605 $matches[2] = ' ' . $matches[2];
608 return '#' . implode('', $rgbcolors) . $matches[2];
611 private function hsl_to_hex($matches)
613 $values = explode(',', str_replace('%', '', $matches[1]));
614 $h = floatval($values[0]);
615 $s = floatval($values[1]);
616 $l = floatval($values[2]);
618 // Wrap and clamp, then fraction!
619 $h = ((($h % 360) + 360) % 360) / 360;
620 $s = $this->clamp_number($s, 0, 100) / 100;
621 $l = $this->clamp_number($l, 0, 100) / 100;
624 $r = $g = $b = $this->round_number(255 * $l);
626 $v2 = $l < 0.5 ? $l * (1 + $s) : ($l + $s) - ($s * $l);
627 $v1 = (2 * $l) - $v2;
628 $r = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h + (1/3)));
629 $g = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h));
630 $b = $this->round_number(255 * $this->hue_to_rgb($v1, $v2, $h - (1/3)));
633 return $this->rgb_to_hex(array('', $r.','.$g.','.$b, $matches[2]));
636 private function lowercase_pseudo_first($matches)
638 return ':first-'. strtolower($matches[1]) .' '. $matches[2];
641 private function lowercase_directives($matches)
643 return '@'. strtolower($matches[1]);
646 private function lowercase_pseudo_elements($matches)
648 return ':'. strtolower($matches[1]);
651 private function lowercase_common_functions($matches)
653 return ':'. strtolower($matches[1]) .'(';
656 private function lowercase_common_functions_values($matches)
658 return $matches[1] . strtolower($matches[2]);
661 private function lowercase_properties($matches)
663 return $matches[1].strtolower($matches[2]).$matches[3];
667 * ---------------------------------------------------------------------------------------------
670 private function hue_to_rgb($v1, $v2, $vh)
672 $vh = $vh < 0 ? $vh + 1 : ($vh > 1 ? $vh - 1 : $vh);
673 if ($vh * 6 < 1) return $v1 + ($v2 - $v1) * 6 * $vh;
674 if ($vh * 2 < 1) return $v2;
675 if ($vh * 3 < 2) return $v1 + ($v2 - $v1) * ((2/3) - $vh) * 6;
679 private function round_number($n)
681 return intval(floor(floatval($n) + 0.5), 10);
684 private function clamp_number($n, $min, $max)
686 return min(max($n, $min), $max);
690 * PHP port of Javascript's "indexOf" function for strings only
691 * Author: Tubal Martin http://blog.margenn.com
693 * @param string $haystack
694 * @param string $needle
695 * @param int $offset index (optional)
698 private function index_of($haystack, $needle, $offset = 0)
700 $index = strpos($haystack, $needle, $offset);
702 return ($index !== FALSE) ? $index : -1;
706 * PHP port of Javascript's "slice" function for strings only
707 * Author: Tubal Martin http://blog.margenn.com
708 * Tests: http://margenn.com/tubal/str_slice/
711 * @param int $start index
712 * @param int|bool $end index (optional)
715 private function str_slice($str, $start = 0, $end = FALSE)
717 if ($end !== FALSE && ($start < 0 || $end <= 0)) {
721 if (($start = $max + $start) < 0) {
727 if (($end = $max + $end) < 0) {
732 if ($end <= $start) {
737 $slice = ($end === FALSE) ? substr($str, $start) : substr($str, $start, $end - $start);
738 return ($slice === FALSE) ? '' : $slice;
742 * Convert strings like "64M" or "30" to int values
746 private function normalize_int($size)
748 if (is_string($size)) {
749 switch (substr($size, -1)) {
750 case 'M': case 'm': return $size * 1048576;
751 case 'K': case 'k': return $size * 1024;
752 case 'G': case 'g': return $size * 1073741824;