Patched to Drupal 8.4.8 level. See https://www.drupal.org/sa-core-2018-004 and patch...
[yaffs-website] / web / core / lib / Drupal / Core / Asset / JsCollectionOptimizer.php
1 <?php
2
3 namespace Drupal\Core\Asset;
4
5 use Drupal\Core\State\StateInterface;
6
7 /**
8  * Optimizes JavaScript assets.
9  */
10 class JsCollectionOptimizer implements AssetCollectionOptimizerInterface {
11
12   /**
13    * A JS asset grouper.
14    *
15    * @var \Drupal\Core\Asset\JsCollectionGrouper
16    */
17   protected $grouper;
18
19   /**
20    * A JS asset optimizer.
21    *
22    * @var \Drupal\Core\Asset\JsOptimizer
23    */
24   protected $optimizer;
25
26   /**
27    * An asset dumper.
28    *
29    * @var \Drupal\Core\Asset\AssetDumper
30    */
31   protected $dumper;
32
33   /**
34    * The state key/value store.
35    *
36    * @var \Drupal\Core\State\StateInterface
37    */
38   protected $state;
39
40   /**
41    * Constructs a JsCollectionOptimizer.
42    *
43    * @param \Drupal\Core\Asset\AssetCollectionGrouperInterface $grouper
44    *   The grouper for JS assets.
45    * @param \Drupal\Core\Asset\AssetOptimizerInterface $optimizer
46    *   The optimizer for a single JS asset.
47    * @param \Drupal\Core\Asset\AssetDumperInterface $dumper
48    *   The dumper for optimized JS assets.
49    * @param \Drupal\Core\State\StateInterface $state
50    *   The state key/value store.
51    */
52   public function __construct(AssetCollectionGrouperInterface $grouper, AssetOptimizerInterface $optimizer, AssetDumperInterface $dumper, StateInterface $state) {
53     $this->grouper = $grouper;
54     $this->optimizer = $optimizer;
55     $this->dumper = $dumper;
56     $this->state = $state;
57   }
58
59   /**
60    * {@inheritdoc}
61    *
62    * The cache file name is retrieved on a page load via a lookup variable that
63    * contains an associative array. The array key is the hash of the names in
64    * $files while the value is the cache file name. The cache file is generated
65    * in two cases. First, if there is no file name value for the key, which will
66    * happen if a new file name has been added to $files or after the lookup
67    * variable is emptied to force a rebuild of the cache. Second, the cache file
68    * is generated if it is missing on disk. Old cache files are not deleted
69    * immediately when the lookup variable is emptied, but are deleted after a
70    * configurable period (@code system.performance.stale_file_threshold @endcode)
71    * to ensure that files referenced by a cached page will still be available.
72    */
73   public function optimize(array $js_assets) {
74     // Group the assets.
75     $js_groups = $this->grouper->group($js_assets);
76
77     // Now optimize (concatenate, not minify) and dump each asset group, unless
78     // that was already done, in which case it should appear in
79     // system.js_cache_files.
80     // Drupal contrib can override this default JS aggregator to keep the same
81     // grouping, optimizing and dumping, but change the strategy that is used to
82     // determine when the aggregate should be rebuilt (e.g. mtime, HTTPS …).
83     $map = $this->state->get('system.js_cache_files') ?: [];
84     $js_assets = [];
85     foreach ($js_groups as $order => $js_group) {
86       // We have to return a single asset, not a group of assets. It is now up
87       // to one of the pieces of code in the switch statement below to set the
88       // 'data' property to the appropriate value.
89       $js_assets[$order] = $js_group;
90       unset($js_assets[$order]['items']);
91
92       switch ($js_group['type']) {
93         case 'file':
94           // No preprocessing, single JS asset: just use the existing URI.
95           if (!$js_group['preprocess']) {
96             $uri = $js_group['items'][0]['data'];
97             $js_assets[$order]['data'] = $uri;
98           }
99           // Preprocess (aggregate), unless the aggregate file already exists.
100           else {
101             $key = $this->generateHash($js_group);
102             $uri = '';
103             if (isset($map[$key])) {
104               $uri = $map[$key];
105             }
106             if (empty($uri) || !file_exists($uri)) {
107               // Concatenate each asset within the group.
108               $data = '';
109               foreach ($js_group['items'] as $js_asset) {
110                 // Optimize this JS file, but only if it's not yet minified.
111                 if (isset($js_asset['minified']) && $js_asset['minified']) {
112                   $data .= file_get_contents($js_asset['data']);
113                 }
114                 else {
115                   $data .= $this->optimizer->optimize($js_asset);
116                 }
117                 // Append a ';' and a newline after each JS file to prevent them
118                 // from running together.
119                 $data .= ";\n";
120               }
121               // Remove unwanted JS code that cause issues.
122               $data = $this->optimizer->clean($data);
123               // Dump the optimized JS for this group into an aggregate file.
124               $uri = $this->dumper->dump($data, 'js');
125               // Set the URI for this group's aggregate file.
126               $js_assets[$order]['data'] = $uri;
127               // Persist the URI for this aggregate file.
128               $map[$key] = $uri;
129               $this->state->set('system.js_cache_files', $map);
130             }
131             else {
132               // Use the persisted URI for the optimized JS file.
133               $js_assets[$order]['data'] = $uri;
134             }
135             $js_assets[$order]['preprocessed'] = TRUE;
136           }
137           break;
138
139         case 'external':
140           // We don't do any aggregation and hence also no caching for external
141           // JS assets.
142           $uri = $js_group['items'][0]['data'];
143           $js_assets[$order]['data'] = $uri;
144           break;
145       }
146     }
147
148     return $js_assets;
149   }
150
151   /**
152    * Generate a hash for a given group of JavaScript assets.
153    *
154    * @param array $js_group
155    *   A group of JavaScript assets.
156    *
157    * @return string
158    *   A hash to uniquely identify the given group of JavaScript assets.
159    */
160   protected function generateHash(array $js_group) {
161     $js_data = [];
162     foreach ($js_group['items'] as $js_file) {
163       $js_data[] = $js_file['data'];
164     }
165     return hash('sha256', serialize($js_data));
166   }
167
168   /**
169    * {@inheritdoc}
170    */
171   public function getAll() {
172     return $this->state->get('system.js_cache_files');
173   }
174
175   /**
176    * {@inheritdoc}
177    */
178   public function deleteAll() {
179     $this->state->delete('system.js_cache_files');
180     $delete_stale = function ($uri) {
181       // Default stale file threshold is 30 days.
182       if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) {
183         file_unmanaged_delete($uri);
184       }
185     };
186     file_scan_directory('public://js', '/.*/', ['callback' => $delete_stale]);
187   }
188
189 }