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