annotate core/lib/Drupal/Core/Asset/CssCollectionOptimizer.php @ 17:129ea1e6d783

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