annotate core/lib/Drupal/Core/Asset/JsCollectionOptimizer.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
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 JavaScript assets.
Chris@0 9 */
Chris@0 10 class JsCollectionOptimizer implements AssetCollectionOptimizerInterface {
Chris@0 11
Chris@0 12 /**
Chris@0 13 * A JS asset grouper.
Chris@0 14 *
Chris@0 15 * @var \Drupal\Core\Asset\JsCollectionGrouper
Chris@0 16 */
Chris@0 17 protected $grouper;
Chris@0 18
Chris@0 19 /**
Chris@0 20 * A JS asset optimizer.
Chris@0 21 *
Chris@0 22 * @var \Drupal\Core\Asset\JsOptimizer
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 JsCollectionOptimizer.
Chris@0 42 *
Chris@0 43 * @param \Drupal\Core\Asset\AssetCollectionGrouperInterface $grouper
Chris@0 44 * The grouper for JS assets.
Chris@0 45 * @param \Drupal\Core\Asset\AssetOptimizerInterface $optimizer
Chris@0 46 * The optimizer for a single JS asset.
Chris@0 47 * @param \Drupal\Core\Asset\AssetDumperInterface $dumper
Chris@0 48 * The dumper for optimized JS 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 names in
Chris@0 64 * $files 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 $files 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 $js_assets) {
Chris@0 74 // Group the assets.
Chris@0 75 $js_groups = $this->grouper->group($js_assets);
Chris@0 76
Chris@0 77 // Now optimize (concatenate, not minify) and dump each asset group, unless
Chris@0 78 // that was already done, in which case it should appear in
Chris@0 79 // system.js_cache_files.
Chris@0 80 // Drupal contrib can override this default JS 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('system.js_cache_files') ?: [];
Chris@0 84 $js_assets = [];
Chris@0 85 foreach ($js_groups as $order => $js_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 $js_assets[$order] = $js_group;
Chris@0 90 unset($js_assets[$order]['items']);
Chris@0 91
Chris@0 92 switch ($js_group['type']) {
Chris@0 93 case 'file':
Chris@0 94 // No preprocessing, single JS asset: just use the existing URI.
Chris@0 95 if (!$js_group['preprocess']) {
Chris@0 96 $uri = $js_group['items'][0]['data'];
Chris@0 97 $js_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($js_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 // Concatenate each asset within the group.
Chris@0 108 $data = '';
Chris@0 109 foreach ($js_group['items'] as $js_asset) {
Chris@0 110 // Optimize this JS file, but only if it's not yet minified.
Chris@0 111 if (isset($js_asset['minified']) && $js_asset['minified']) {
Chris@0 112 $data .= file_get_contents($js_asset['data']);
Chris@0 113 }
Chris@0 114 else {
Chris@0 115 $data .= $this->optimizer->optimize($js_asset);
Chris@0 116 }
Chris@0 117 // Append a ';' and a newline after each JS file to prevent them
Chris@0 118 // from running together.
Chris@0 119 $data .= ";\n";
Chris@0 120 }
Chris@0 121 // Remove unwanted JS code that cause issues.
Chris@0 122 $data = $this->optimizer->clean($data);
Chris@0 123 // Dump the optimized JS for this group into an aggregate file.
Chris@0 124 $uri = $this->dumper->dump($data, 'js');
Chris@0 125 // Set the URI for this group's aggregate file.
Chris@0 126 $js_assets[$order]['data'] = $uri;
Chris@0 127 // Persist the URI for this aggregate file.
Chris@0 128 $map[$key] = $uri;
Chris@0 129 $this->state->set('system.js_cache_files', $map);
Chris@0 130 }
Chris@0 131 else {
Chris@0 132 // Use the persisted URI for the optimized JS file.
Chris@0 133 $js_assets[$order]['data'] = $uri;
Chris@0 134 }
Chris@0 135 $js_assets[$order]['preprocessed'] = TRUE;
Chris@0 136 }
Chris@0 137 break;
Chris@0 138
Chris@0 139 case 'external':
Chris@0 140 // We don't do any aggregation and hence also no caching for external
Chris@0 141 // JS assets.
Chris@0 142 $uri = $js_group['items'][0]['data'];
Chris@0 143 $js_assets[$order]['data'] = $uri;
Chris@0 144 break;
Chris@0 145 }
Chris@0 146 }
Chris@0 147
Chris@0 148 return $js_assets;
Chris@0 149 }
Chris@0 150
Chris@0 151 /**
Chris@0 152 * Generate a hash for a given group of JavaScript assets.
Chris@0 153 *
Chris@0 154 * @param array $js_group
Chris@0 155 * A group of JavaScript assets.
Chris@0 156 *
Chris@0 157 * @return string
Chris@0 158 * A hash to uniquely identify the given group of JavaScript assets.
Chris@0 159 */
Chris@0 160 protected function generateHash(array $js_group) {
Chris@0 161 $js_data = [];
Chris@0 162 foreach ($js_group['items'] as $js_file) {
Chris@0 163 $js_data[] = $js_file['data'];
Chris@0 164 }
Chris@0 165 return hash('sha256', serialize($js_data));
Chris@0 166 }
Chris@0 167
Chris@0 168 /**
Chris@0 169 * {@inheritdoc}
Chris@0 170 */
Chris@0 171 public function getAll() {
Chris@0 172 return $this->state->get('system.js_cache_files');
Chris@0 173 }
Chris@0 174
Chris@0 175 /**
Chris@0 176 * {@inheritdoc}
Chris@0 177 */
Chris@0 178 public function deleteAll() {
Chris@0 179 $this->state->delete('system.js_cache_files');
Chris@0 180 $delete_stale = function ($uri) {
Chris@0 181 // Default stale file threshold is 30 days.
Chris@0 182 if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) {
Chris@0 183 file_unmanaged_delete($uri);
Chris@0 184 }
Chris@0 185 };
Chris@0 186 file_scan_directory('public://js', '/.*/', ['callback' => $delete_stale]);
Chris@0 187 }
Chris@0 188
Chris@0 189 }