function CssCollectionOptimizerLazy::optimizeGroup

Same name and namespace in other branches
  1. 11.x core/lib/Drupal/Core/Asset/CssCollectionOptimizerLazy.php \Drupal\Core\Asset\CssCollectionOptimizerLazy::optimizeGroup()
  2. 10 core/lib/Drupal/Core/Asset/CssCollectionOptimizerLazy.php \Drupal\Core\Asset\CssCollectionOptimizerLazy::optimizeGroup()

Optimizes a specific group of assets.

Parameters

array $group: An asset group.

Return value

string The optimized string for the group.

Overrides AssetCollectionGroupOptimizerInterface::optimizeGroup

File

core/lib/Drupal/Core/Asset/CssCollectionOptimizerLazy.php, line 150

Class

CssCollectionOptimizerLazy
Optimizes CSS assets.

Namespace

Drupal\Core\Asset

Code

public function optimizeGroup(array $group) : string {
  // Optimize each asset within the group.
  $data = '';
  $current_license = FALSE;
  foreach ($group['items'] as $css_asset) {
    // Ensure license information is available as a comment after
    // optimization.
    if ($css_asset['license'] !== $current_license) {
      $data .= "/* @license " . $css_asset['license']['name'] . " " . $css_asset['license']['url'] . " */\n";
    }
    $current_license = $css_asset['license'];
    // Only external minified files can skip optimization.
    // Local files (even if minified) must be processed to ensure resource
    // paths are rewritten relative to the cached aggregated file location.
    $is_minified = isset($css_asset['minified']) && $css_asset['minified'];
    $is_external = isset($css_asset['type']) && $css_asset['type'] === 'external';
    if ($is_minified && $is_external) {
      $data .= file_get_contents($css_asset['data']);
    }
    else {
      $data .= $this->optimizer
        ->optimize($css_asset);
    }
  }
  // Per the W3C specification at
  // https://www.w3.org/TR/REC-CSS2/cascade.html#at-import, @import rules must
  // precede any other style, so we move those to the top. The regular
  // expression is expressed in NOWDOC since it is detecting backslashes as
  // well as single and double quotes. It is difficult to read when
  // represented as a quoted string.
  $regexp = <<<'REGEXP'
  /@import\s*(?:'(?:\\'|.)*'|"(?:\\"|.)*"|url\(\s*(?:\\[\)\'\"]|[^'")])*\s*\)|url\(\s*'(?:\'|.)*'\s*\)|url\(\s*"(?:\"|.)*"\s*\)).*;/iU
  REGEXP;
  preg_match_all($regexp, $data, $matches);
  $data = preg_replace($regexp, '', $data);
  return implode('', $matches[0]) . (!empty($matches[0]) ? "\n" : '') . $data;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.