1<?php 2 3namespace Drupal\Core\Asset; 4 5use Drupal\Core\File\FileSystemInterface; 6use Drupal\Core\State\StateInterface; 7 8/** 9 * Optimizes CSS assets. 10 */ 11class CssCollectionOptimizer implements AssetCollectionOptimizerInterface { 12 13 /** 14 * A CSS asset grouper. 15 * 16 * @var \Drupal\Core\Asset\CssCollectionGrouper 17 */ 18 protected $grouper; 19 20 /** 21 * A CSS asset optimizer. 22 * 23 * @var \Drupal\Core\Asset\CssOptimizer 24 */ 25 protected $optimizer; 26 27 /** 28 * An asset dumper. 29 * 30 * @var \Drupal\Core\Asset\AssetDumper 31 */ 32 protected $dumper; 33 34 /** 35 * The state key/value store. 36 * 37 * @var \Drupal\Core\State\StateInterface 38 */ 39 protected $state; 40 41 /** 42 * The file system service. 43 * 44 * @var \Drupal\Core\File\FileSystemInterface 45 */ 46 protected $fileSystem; 47 48 /** 49 * Constructs a CssCollectionOptimizer. 50 * 51 * @param \Drupal\Core\Asset\AssetCollectionGrouperInterface $grouper 52 * The grouper for CSS assets. 53 * @param \Drupal\Core\Asset\AssetOptimizerInterface $optimizer 54 * The optimizer for a single CSS asset. 55 * @param \Drupal\Core\Asset\AssetDumperInterface $dumper 56 * The dumper for optimized CSS assets. 57 * @param \Drupal\Core\State\StateInterface $state 58 * The state key/value store. 59 * @param \Drupal\Core\File\FileSystemInterface $file_system 60 * The file system service. 61 */ 62 public function __construct(AssetCollectionGrouperInterface $grouper, AssetOptimizerInterface $optimizer, AssetDumperInterface $dumper, StateInterface $state, FileSystemInterface $file_system) { 63 $this->grouper = $grouper; 64 $this->optimizer = $optimizer; 65 $this->dumper = $dumper; 66 $this->state = $state; 67 $this->fileSystem = $file_system; 68 } 69 70 /** 71 * {@inheritdoc} 72 * 73 * The cache file name is retrieved on a page load via a lookup variable that 74 * contains an associative array. The array key is the hash of the file names 75 * in $css while the value is the cache file name. The cache file is generated 76 * in two cases. First, if there is no file name value for the key, which will 77 * happen if a new file name has been added to $css or after the lookup 78 * variable is emptied to force a rebuild of the cache. Second, the cache file 79 * is generated if it is missing on disk. Old cache files are not deleted 80 * immediately when the lookup variable is emptied, but are deleted after a 81 * configurable period (@code system.performance.stale_file_threshold @endcode) 82 * to ensure that files referenced by a cached page will still be available. 83 */ 84 public function optimize(array $css_assets) { 85 // Group the assets. 86 $css_groups = $this->grouper->group($css_assets); 87 88 // Now optimize (concatenate + minify) and dump each asset group, unless 89 // that was already done, in which case it should appear in 90 // drupal_css_cache_files. 91 // Drupal contrib can override this default CSS aggregator to keep the same 92 // grouping, optimizing and dumping, but change the strategy that is used to 93 // determine when the aggregate should be rebuilt (e.g. mtime, HTTPS …). 94 $map = $this->state->get('drupal_css_cache_files', []); 95 $css_assets = []; 96 foreach ($css_groups as $order => $css_group) { 97 // We have to return a single asset, not a group of assets. It is now up 98 // to one of the pieces of code in the switch statement below to set the 99 // 'data' property to the appropriate value. 100 $css_assets[$order] = $css_group; 101 unset($css_assets[$order]['items']); 102 103 switch ($css_group['type']) { 104 case 'file': 105 // No preprocessing, single CSS asset: just use the existing URI. 106 if (!$css_group['preprocess']) { 107 $uri = $css_group['items'][0]['data']; 108 $css_assets[$order]['data'] = $uri; 109 } 110 // Preprocess (aggregate), unless the aggregate file already exists. 111 else { 112 $key = $this->generateHash($css_group); 113 $uri = ''; 114 if (isset($map[$key])) { 115 $uri = $map[$key]; 116 } 117 if (empty($uri) || !file_exists($uri)) { 118 // Optimize each asset within the group. 119 $data = ''; 120 foreach ($css_group['items'] as $css_asset) { 121 $data .= $this->optimizer->optimize($css_asset); 122 } 123 // Per the W3C specification at 124 // http://www.w3.org/TR/REC-CSS2/cascade.html#at-import, @import 125 // rules must precede any other style, so we move those to the 126 // top. The regular expression is expressed in NOWDOC since it is 127 // detecting backslashes as well as single and double quotes. It 128 // is difficult to read when represented as a quoted string. 129 $regexp = <<<'REGEXP' 130/@import\s*(?:'(?:\\'|.)*'|"(?:\\"|.)*"|url\(\s*(?:\\[\)\'\"]|[^'")])*\s*\)|url\(\s*'(?:\'|.)*'\s*\)|url\(\s*"(?:\"|.)*"\s*\)).*;/iU 131REGEXP; 132 preg_match_all($regexp, $data, $matches); 133 $data = preg_replace($regexp, '', $data); 134 $data = implode('', $matches[0]) . $data; 135 // Dump the optimized CSS for this group into an aggregate file. 136 $uri = $this->dumper->dump($data, 'css'); 137 // Set the URI for this group's aggregate file. 138 $css_assets[$order]['data'] = $uri; 139 // Persist the URI for this aggregate file. 140 $map[$key] = $uri; 141 $this->state->set('drupal_css_cache_files', $map); 142 } 143 else { 144 // Use the persisted URI for the optimized CSS file. 145 $css_assets[$order]['data'] = $uri; 146 } 147 $css_assets[$order]['preprocessed'] = TRUE; 148 } 149 break; 150 151 case 'external': 152 // We don't do any aggregation and hence also no caching for external 153 // CSS assets. 154 $uri = $css_group['items'][0]['data']; 155 $css_assets[$order]['data'] = $uri; 156 break; 157 } 158 } 159 160 return $css_assets; 161 } 162 163 /** 164 * Generate a hash for a given group of CSS assets. 165 * 166 * @param array $css_group 167 * A group of CSS assets. 168 * 169 * @return string 170 * A hash to uniquely identify the given group of CSS assets. 171 */ 172 protected function generateHash(array $css_group) { 173 $css_data = []; 174 foreach ($css_group['items'] as $css_file) { 175 $css_data[] = $css_file['data']; 176 } 177 return hash('sha256', serialize($css_data)); 178 } 179 180 /** 181 * {@inheritdoc} 182 */ 183 public function getAll() { 184 return $this->state->get('drupal_css_cache_files'); 185 } 186 187 /** 188 * {@inheritdoc} 189 */ 190 public function deleteAll() { 191 $this->state->delete('drupal_css_cache_files'); 192 193 $delete_stale = function ($uri) { 194 // Default stale file threshold is 30 days. 195 if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) { 196 $this->fileSystem->delete($uri); 197 } 198 }; 199 if (is_dir('public://css')) { 200 $this->fileSystem->scanDirectory('public://css', '/.*/', ['callback' => $delete_stale]); 201 } 202 } 203 204} 205