annotate core/lib/Drupal/Core/Asset/JsCollectionOptimizer.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 JavaScript assets.
Chris@0 10 */
Chris@0 11 class JsCollectionOptimizer implements AssetCollectionOptimizerInterface {
Chris@0 12
Chris@0 13 /**
Chris@0 14 * A JS asset grouper.
Chris@0 15 *
Chris@0 16 * @var \Drupal\Core\Asset\JsCollectionGrouper
Chris@0 17 */
Chris@0 18 protected $grouper;
Chris@0 19
Chris@0 20 /**
Chris@0 21 * A JS asset optimizer.
Chris@0 22 *
Chris@0 23 * @var \Drupal\Core\Asset\JsOptimizer
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 JsCollectionOptimizer.
Chris@0 50 *
Chris@0 51 * @param \Drupal\Core\Asset\AssetCollectionGrouperInterface $grouper
Chris@0 52 * The grouper for JS assets.
Chris@0 53 * @param \Drupal\Core\Asset\AssetOptimizerInterface $optimizer
Chris@0 54 * The optimizer for a single JS asset.
Chris@0 55 * @param \Drupal\Core\Asset\AssetDumperInterface $dumper
Chris@0 56 * The dumper for optimized JS 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 JsCollectionOptimizer::__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 names in
Chris@0 79 * $files 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 $files 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 $js_assets) {
Chris@0 89 // Group the assets.
Chris@0 90 $js_groups = $this->grouper->group($js_assets);
Chris@0 91
Chris@0 92 // Now optimize (concatenate, not minify) and dump each asset group, unless
Chris@0 93 // that was already done, in which case it should appear in
Chris@0 94 // system.js_cache_files.
Chris@0 95 // Drupal contrib can override this default JS 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('system.js_cache_files') ?: [];
Chris@0 99 $js_assets = [];
Chris@0 100 foreach ($js_groups as $order => $js_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 $js_assets[$order] = $js_group;
Chris@0 105 unset($js_assets[$order]['items']);
Chris@0 106
Chris@0 107 switch ($js_group['type']) {
Chris@0 108 case 'file':
Chris@0 109 // No preprocessing, single JS asset: just use the existing URI.
Chris@0 110 if (!$js_group['preprocess']) {
Chris@0 111 $uri = $js_group['items'][0]['data'];
Chris@0 112 $js_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($js_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 // Concatenate each asset within the group.
Chris@0 123 $data = '';
Chris@0 124 foreach ($js_group['items'] as $js_asset) {
Chris@0 125 // Optimize this JS file, but only if it's not yet minified.
Chris@0 126 if (isset($js_asset['minified']) && $js_asset['minified']) {
Chris@0 127 $data .= file_get_contents($js_asset['data']);
Chris@0 128 }
Chris@0 129 else {
Chris@0 130 $data .= $this->optimizer->optimize($js_asset);
Chris@0 131 }
Chris@0 132 // Append a ';' and a newline after each JS file to prevent them
Chris@0 133 // from running together.
Chris@0 134 $data .= ";\n";
Chris@0 135 }
Chris@0 136 // Remove unwanted JS code that cause issues.
Chris@0 137 $data = $this->optimizer->clean($data);
Chris@0 138 // Dump the optimized JS for this group into an aggregate file.
Chris@0 139 $uri = $this->dumper->dump($data, 'js');
Chris@0 140 // Set the URI for this group's aggregate file.
Chris@0 141 $js_assets[$order]['data'] = $uri;
Chris@0 142 // Persist the URI for this aggregate file.
Chris@0 143 $map[$key] = $uri;
Chris@0 144 $this->state->set('system.js_cache_files', $map);
Chris@0 145 }
Chris@0 146 else {
Chris@0 147 // Use the persisted URI for the optimized JS file.
Chris@0 148 $js_assets[$order]['data'] = $uri;
Chris@0 149 }
Chris@0 150 $js_assets[$order]['preprocessed'] = TRUE;
Chris@0 151 }
Chris@0 152 break;
Chris@0 153
Chris@0 154 case 'external':
Chris@0 155 // We don't do any aggregation and hence also no caching for external
Chris@0 156 // JS assets.
Chris@0 157 $uri = $js_group['items'][0]['data'];
Chris@0 158 $js_assets[$order]['data'] = $uri;
Chris@0 159 break;
Chris@0 160 }
Chris@0 161 }
Chris@0 162
Chris@0 163 return $js_assets;
Chris@0 164 }
Chris@0 165
Chris@0 166 /**
Chris@0 167 * Generate a hash for a given group of JavaScript assets.
Chris@0 168 *
Chris@0 169 * @param array $js_group
Chris@0 170 * A group of JavaScript assets.
Chris@0 171 *
Chris@0 172 * @return string
Chris@0 173 * A hash to uniquely identify the given group of JavaScript assets.
Chris@0 174 */
Chris@0 175 protected function generateHash(array $js_group) {
Chris@0 176 $js_data = [];
Chris@0 177 foreach ($js_group['items'] as $js_file) {
Chris@0 178 $js_data[] = $js_file['data'];
Chris@0 179 }
Chris@0 180 return hash('sha256', serialize($js_data));
Chris@0 181 }
Chris@0 182
Chris@0 183 /**
Chris@0 184 * {@inheritdoc}
Chris@0 185 */
Chris@0 186 public function getAll() {
Chris@0 187 return $this->state->get('system.js_cache_files');
Chris@0 188 }
Chris@0 189
Chris@0 190 /**
Chris@0 191 * {@inheritdoc}
Chris@0 192 */
Chris@0 193 public function deleteAll() {
Chris@0 194 $this->state->delete('system.js_cache_files');
Chris@0 195 $delete_stale = function ($uri) {
Chris@0 196 // Default stale file threshold is 30 days.
Chris@0 197 if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) {
Chris@18 198 $this->fileSystem->delete($uri);
Chris@0 199 }
Chris@0 200 };
Chris@0 201 file_scan_directory('public://js', '/.*/', ['callback' => $delete_stale]);
Chris@0 202 }
Chris@0 203
Chris@0 204 }