You are here

private function CSSmin::compress_hex_colors in Advanced CSS/JS Aggregation 8.2

Same name and namespace in other branches
  1. 8.3 advagg_css_minify/yui/CSSMin.inc \CSSmin::compress_hex_colors()
  2. 6 advagg_css_compress/yui/CSSMin.inc \CSSmin::compress_hex_colors()

Utility method to compress hex color values of the form #AABBCC to #ABC or short color name.

DOES NOT compress CSS ID selectors which match the above pattern (which would break things). e.g. #AddressForm { ... }

DOES NOT compress IE filters, which have hex color values (which would break things). e.g. filter: chroma(color="#FFFFFF");

DOES NOT compress invalid hex values. e.g. background-color: #aabbccdd

Parameters

string $css:

Return value

string

1 call to CSSmin::compress_hex_colors()
CSSmin::minify in advagg_css_minify/yui/CSSMin.inc
Does bulk of the minification

File

advagg_css_minify/yui/CSSMin.inc, line 518

Class

CSSmin

Code

private function compress_hex_colors($css) {

  // Look for hex colors inside { ... } (to avoid IDs) and which don't have a =, or a " in front of them (to avoid filters)
  $pattern = '/(\\=\\s*?["\']?)?#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])(\\}|[^0-9a-f{][^{]*?\\})/iS';
  $_index = $index = $last_index = $offset = 0;
  $sb = array();

  // See: http://ajaxmin.codeplex.com/wikipage?title=CSS%20Colors
  $short_safe = array(
    '#808080' => 'gray',
    '#008000' => 'green',
    '#800000' => 'maroon',
    '#000080' => 'navy',
    '#808000' => 'olive',
    '#ffa500' => 'orange',
    '#800080' => 'purple',
    '#c0c0c0' => 'silver',
    '#008080' => 'teal',
    '#f00' => 'red',
  );
  while (preg_match($pattern, $css, $m, 0, $offset)) {
    $index = $this
      ->index_of($css, $m[0], $offset);
    $last_index = $index + strlen($m[0]);
    $is_filter = $m[1] !== null && $m[1] !== '';
    $sb[] = $this
      ->str_slice($css, $_index, $index);
    if ($is_filter) {

      // Restore, maintain case, otherwise filter will break
      $sb[] = $m[1] . '#' . $m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7];
    }
    else {
      if (strtolower($m[2]) == strtolower($m[3]) && strtolower($m[4]) == strtolower($m[5]) && strtolower($m[6]) == strtolower($m[7])) {

        // Compress.
        $hex = '#' . strtolower($m[3] . $m[5] . $m[7]);
      }
      else {

        // Non compressible color, restore but lower case.
        $hex = '#' . strtolower($m[2] . $m[3] . $m[4] . $m[5] . $m[6] . $m[7]);
      }

      // replace Hex colors to short safe color names
      $sb[] = array_key_exists($hex, $short_safe) ? $short_safe[$hex] : $hex;
    }
    $_index = $offset = $last_index - strlen($m[8]);
  }
  $sb[] = $this
    ->str_slice($css, $_index);
  return implode('', $sb);
}