annotate core/lib/Drupal/Core/Asset/CssCollectionOptimizer.php @ 19:fa3358dc1485 tip

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