Yaffs site version 1.1
[yaffs-website] / web / modules / contrib / advagg / src / Asset / JsCollectionOptimizer.php
1 <?php
2
3 namespace Drupal\advagg\Asset;
4
5 use Drupal\Core\Asset\AssetCollectionGrouperInterface;
6 use Drupal\Core\Asset\AssetCollectionOptimizerInterface;
7 use Drupal\Core\Asset\AssetDumperInterface;
8 use Drupal\Core\Asset\AssetOptimizerInterface;
9 use Drupal\Core\Asset\JsCollectionOptimizer as CoreJsCollectionOptimizer;
10 use Drupal\Core\Cache\Cache;
11 use Drupal\Core\Extension\ModuleHandlerInterface;
12 use Drupal\Core\Config\ConfigFactoryInterface;
13 use Drupal\Core\State\StateInterface;
14
15 /**
16  * {@inheritdoc}
17  */
18 class JsCollectionOptimizer extends CoreJsCollectionOptimizer implements AssetCollectionOptimizerInterface {
19
20   /**
21    * A config object for the advagg configuration.
22    *
23    * @var \Drupal\Core\Config\Config
24    */
25   protected $config;
26
27   /**
28    * A config object for the system performance configuration.
29    *
30    * @var \Drupal\Core\Config\Config
31    */
32   protected $systemConfig;
33
34   /**
35    * A state information store for the AdvAgg generated aggregates.
36    *
37    * @var \Drupal\Core\State\StateInterface
38    */
39   protected $advaggAggregates;
40
41   /**
42    * Module handler service.
43    *
44    * @var \Drupal\Core\Extension\ModuleHandlerInterface
45    */
46   protected $moduleHandler;
47
48   /**
49    * Hash of the AdvAgg settings.
50    *
51    * @var string
52    */
53   protected $settingsHash;
54
55   /**
56    * {@inheritdoc}
57    *
58    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
59    *   A config factory for retrieving required config objects.
60    * @param \Drupal\Core\State\StateInterface $advagg_aggregates
61    *   A state information store for the AdvAgg generated aggregates.
62    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
63    *   The module handler.
64    */
65   public function __construct(AssetCollectionGrouperInterface $grouper, AssetOptimizerInterface $optimizer, AssetDumperInterface $dumper, StateInterface $state, ConfigFactoryInterface $config_factory, StateInterface $advagg_aggregates, ModuleHandlerInterface $module_handler) {
66     $this->grouper = $grouper;
67     $this->optimizer = $optimizer;
68     $this->dumper = $dumper;
69     $this->state = $state;
70     $this->config = $config_factory->get('advagg.settings');
71     $this->systemConfig = $config_factory->get('system.performance');
72     $this->advaggAggregates = $advagg_aggregates;
73     $this->moduleHandler = $module_handler;
74     $this->settingsHash = '_' . advagg_get_current_hooks_hash();
75   }
76
77   /**
78    * {@inheritdoc}
79    */
80   public function optimize(array $js_assets) {
81     // Group the assets.
82     $js_groups = $this->grouper->group($js_assets);
83
84     // Now optimize (concatenate, not minify) and dump each asset group, unless
85     // that was already done, in which case it should appear in
86     // system.js_cache_files.
87     // Drupal contrib can override this default JS aggregator to keep the same
88     // grouping, optimizing and dumping, but change the strategy that is used to
89     // determine when the aggregate should be rebuilt (e.g. mtime, HTTPS …).
90     $js_assets = [];
91     $protocol_relative = $this->config->get('path.convert.absolute_to_protocol_relative');
92     $force_https = $this->config->get('path.convert.force_https');
93     foreach ($js_groups as $order => $js_group) {
94       // We have to return a single asset, not a group of assets. It is now up
95       // to one of the pieces of code in the switch statement below to set the
96       // 'data' property to the appropriate value.
97       $js_assets[$order] = $js_group;
98       unset($js_assets[$order]['items']);
99
100       switch ($js_group['type']) {
101         case 'file':
102           // No preprocessing, single JS asset: just use the existing URI.
103           if (!$js_group['preprocess']) {
104             $js_assets[$order]['data'] = $js_group['items'][0]['data'];
105           }
106           // Preprocess (aggregate), unless the aggregate file already exists.
107           else {
108             $key = $this->generateHash($js_group) . $this->settingsHash;
109             $uri = '';
110             if ($aggregate = $this->advaggAggregates->get($key)) {
111               $uri = $aggregate['uri'];
112             }
113             if (empty($uri) || !file_exists($uri)) {
114               // Concatenate each asset within the group.
115               $data = '';
116               foreach ($js_group['items'] as $js_asset) {
117                 // Optimize this JS file, but only if it's not yet minified.
118                 if (isset($js_asset['minified']) && $js_asset['minified']) {
119                   $content = file_get_contents($js_asset['data']);
120                 }
121                 else {
122                   $content = $this->optimizer->optimize($js_asset);
123                 }
124
125                 // Allow other modules to modify this file's contents.
126                 // Call hook_advagg_js_contents_alter().
127                 $this->moduleHandler->alter('advagg_js_contents', $content, $js_asset);
128                 $data .= $content;
129
130                 // Append a ';' and a newline after each JS file to prevent them
131                 // from running together.
132                 $data .= ";\n";
133               }
134               // Remove unwanted JS code that cause issues.
135               $data = $this->optimizer->clean($data);
136               // Dump the optimized JS for this group into an aggregate file.
137               list($uri, $filename) = $this->dumper->dump($data, 'js');
138               // Set the URI for this group's aggregate file.
139               $js_assets[$order]['data'] = $uri;
140               // Persist the URI for this aggregate file.
141               $aggregate_info = [
142                 'uri' => $uri,
143                 'contents' => $js_group['items'],
144                 'hooks_hash' => advagg_current_hooks_hash_array(),
145                 'uid' => $filename,
146               ];
147               $this->advaggAggregates->set($key, $aggregate_info);
148             }
149             else {
150               // Use the persisted URI for the optimized JS file.
151               $js_assets[$order]['data'] = $uri;
152             }
153             $js_assets[$order]['preprocessed'] = TRUE;
154           }
155           break;
156
157         case 'external':
158           // We don't do any aggregation and hence also no caching for external
159           // JS assets.
160           $uri = $js_group['items'][0]['data'];
161           if ($force_https) {
162             $uri = advagg_path_convert_force_https($uri);
163           }
164           elseif ($protocol_relative) {
165             $uri = advagg_path_convert_protocol_relative($uri);
166           }
167           $js_assets[$order]['data'] = $uri;
168           break;
169       }
170     }
171
172     return $js_assets;
173   }
174
175   /**
176    * Generate a hash for a given group of JavaScript assets.
177    *
178    * @param array $js_group
179    *   A group of JavaScript assets.
180    *
181    * @return string
182    *   A hash to uniquely identify the given group of JavaScript assets.
183    */
184   protected function generateHash(array $js_group) {
185     $js_data = [];
186     foreach ($js_group['items'] as $js_file) {
187       $js_data[] = $js_file['data'];
188       $js_data[] = filemtime($js_file['data']);
189     }
190     return hash('sha256', serialize($js_data));
191   }
192
193   /**
194    * Deletes all optimized collection assets.
195    *
196    * Note: Core's deleteAll() only deletes old files not all.
197    */
198   public function deleteAllReal() {
199     $log = [];
200     $this->state->delete('system.js_cache_files');
201     Cache::invalidateTags(['library_info']);
202     $delete_all = function ($uri) use (&$log) {
203       file_unmanaged_delete($uri);
204       $log[] = $uri;
205     };
206     $this->state->delete('system.js_cache_files');
207     file_scan_directory($this->dumper->preparePath('js'), '/.*/', ['callback' => $delete_all]);
208     return $log;
209   }
210
211   /**
212    * Delete stale optimized collection assets.
213    */
214   public function deleteStale() {
215     $log = [];
216     $this->state->delete('system.js_cache_files');
217     Cache::invalidateTags(['library_info']);
218     $delete_stale = function ($uri) use (&$log) {
219       // Default stale file threshold is 30 days.
220       if (REQUEST_TIME - fileatime($uri) > $this->systemConfig->get('stale_file_threshold')) {
221         file_unmanaged_delete($uri);
222         $log[] = $uri;
223       }
224     };
225     file_scan_directory($this->dumper->preparePath('js'), '/.*/', ['callback' => $delete_stale]);
226     return $log;
227   }
228
229   /**
230    * Delete old optimized collection assets.
231    */
232   public function deleteOld() {
233     $log = [];
234     $this->state->delete('system.js_cache_files');
235     Cache::invalidateTags(['library_info']);
236     $delete_old = function ($uri) use (&$log) {
237       // Default stale file threshold is 30 days.
238       // Delete old if > 3 times that.
239       if (REQUEST_TIME - filemtime($uri) > $this->systemConfig->get('stale_file_threshold') * 3) {
240         file_unmanaged_delete($uri);
241         $log[] = $uri;
242       }
243     };
244     file_scan_directory($this->dumper->preparePath('js'), '/.*/', ['callback' => $delete_old]);
245     return $log;
246   }
247
248 }