3 namespace Drupal\advagg\Asset;
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;
18 class JsCollectionOptimizer extends CoreJsCollectionOptimizer implements AssetCollectionOptimizerInterface {
21 * A config object for the advagg configuration.
23 * @var \Drupal\Core\Config\Config
28 * A config object for the system performance configuration.
30 * @var \Drupal\Core\Config\Config
32 protected $systemConfig;
35 * A state information store for the AdvAgg generated aggregates.
37 * @var \Drupal\Core\State\StateInterface
39 protected $advaggAggregates;
42 * Module handler service.
44 * @var \Drupal\Core\Extension\ModuleHandlerInterface
46 protected $moduleHandler;
49 * Hash of the AdvAgg settings.
53 protected $settingsHash;
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
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();
80 public function optimize(array $js_assets) {
82 $js_groups = $this->grouper->group($js_assets);
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 …).
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']);
100 switch ($js_group['type']) {
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'];
106 // Preprocess (aggregate), unless the aggregate file already exists.
108 $key = $this->generateHash($js_group) . $this->settingsHash;
110 if ($aggregate = $this->advaggAggregates->get($key)) {
111 $uri = $aggregate['uri'];
113 if (empty($uri) || !file_exists($uri)) {
114 // Concatenate each asset within the group.
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']);
122 $content = $this->optimizer->optimize($js_asset);
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);
130 // Append a ';' and a newline after each JS file to prevent them
131 // from running together.
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.
143 'contents' => $js_group['items'],
144 'hooks_hash' => advagg_current_hooks_hash_array(),
147 $this->advaggAggregates->set($key, $aggregate_info);
150 // Use the persisted URI for the optimized JS file.
151 $js_assets[$order]['data'] = $uri;
153 $js_assets[$order]['preprocessed'] = TRUE;
158 // We don't do any aggregation and hence also no caching for external
160 $uri = $js_group['items'][0]['data'];
162 $uri = advagg_path_convert_force_https($uri);
164 elseif ($protocol_relative) {
165 $uri = advagg_path_convert_protocol_relative($uri);
167 $js_assets[$order]['data'] = $uri;
176 * Generate a hash for a given group of JavaScript assets.
178 * @param array $js_group
179 * A group of JavaScript assets.
182 * A hash to uniquely identify the given group of JavaScript assets.
184 protected function generateHash(array $js_group) {
186 foreach ($js_group['items'] as $js_file) {
187 $js_data[] = $js_file['data'];
188 $js_data[] = filemtime($js_file['data']);
190 return hash('sha256', serialize($js_data));
194 * Deletes all optimized collection assets.
196 * Note: Core's deleteAll() only deletes old files not all.
198 public function deleteAllReal() {
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);
206 $this->state->delete('system.js_cache_files');
207 file_scan_directory($this->dumper->preparePath('js'), '/.*/', ['callback' => $delete_all]);
212 * Delete stale optimized collection assets.
214 public function deleteStale() {
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);
225 file_scan_directory($this->dumper->preparePath('js'), '/.*/', ['callback' => $delete_stale]);
230 * Delete old optimized collection assets.
232 public function deleteOld() {
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);
244 file_scan_directory($this->dumper->preparePath('js'), '/.*/', ['callback' => $delete_old]);