Yaffs site version 1.1
[yaffs-website] / web / modules / contrib / advagg / src / Asset / CssCollectionOptimizer.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\CssCollectionOptimizer as CoreCssCollectionOptimizer;
10 use Drupal\Core\Extension\ModuleHandlerInterface;
11 use Drupal\Core\Cache\Cache;
12 use Drupal\Core\Config\ConfigFactoryInterface;
13 use Drupal\Core\State\StateInterface;
14 use Symfony\Component\HttpFoundation\RequestStack;
15
16 /**
17  * {@inheritdoc}
18  */
19 class CssCollectionOptimizer extends CoreCssCollectionOptimizer implements AssetCollectionOptimizerInterface {
20
21   /**
22    * A config object for the advagg configuration.
23    *
24    * @var \Drupal\Core\Config\Config
25    */
26   protected $config;
27
28   /**
29    * A config object for the system performance configuration.
30    *
31    * @var \Drupal\Core\Config\Config
32    */
33   protected $systemConfig;
34
35   /**
36    * A state information store for the AdvAgg generated aggregates.
37    *
38    * @var \Drupal\Core\State\StateInterface
39    */
40   protected $advaggAggregates;
41
42   /**
43    * Module handler service.
44    *
45    * @var \Drupal\Core\Extension\ModuleHandlerInterface
46    */
47   protected $moduleHandler;
48
49   /**
50    * The AdvAgg file status state information storage service.
51    *
52    * @var \Drupal\Core\State\StateInterface
53    */
54   protected $advaggFiles;
55
56   /**
57    * Hash of the AdvAgg settings.
58    *
59    * @var string
60    */
61   protected $settingsHash;
62
63   /**
64    * The request stack.
65    *
66    * @var \Symfony\Component\HttpFoundation\RequestStack
67    */
68   protected $requestStack;
69
70   /**
71    * {@inheritdoc}
72    *
73    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
74    *   A config factory for retrieving required config objects.
75    * @param \Drupal\Core\State\StateInterface $advagg_aggregates
76    *   A state information store for the AdvAgg generated aggregates.
77    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
78    *   The module handler.
79    * @param \Drupal\Core\State\StateInterface $advagg_files
80    *   The AdvAgg file status state information storage service.
81    * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
82    *   The request stack.
83    */
84   public function __construct(AssetCollectionGrouperInterface $grouper, AssetOptimizerInterface $optimizer, AssetDumperInterface $dumper, StateInterface $state, ConfigFactoryInterface $config_factory, StateInterface $advagg_aggregates, ModuleHandlerInterface $module_handler, StateInterface $advagg_files, RequestStack $request_stack) {
85     $this->grouper = $grouper;
86     $this->optimizer = $optimizer;
87     $this->dumper = $dumper;
88     $this->state = $state;
89     $this->config = $config_factory->get('advagg.settings');
90     $this->systemConfig = $config_factory->get('system.performance');
91     $this->advaggAggregates = $advagg_aggregates;
92     $this->moduleHandler = $module_handler;
93     $this->advaggFiles = $advagg_files;
94     $this->settingsHash = '_' . advagg_get_current_hooks_hash();
95     $this->requestStack = $request_stack;
96   }
97
98   /**
99    * {@inheritdoc}
100    */
101   public function optimize(array $css_assets) {
102     // Group the assets.
103     $css_groups = $this->grouper->group($css_assets);
104
105     // Now optimize (concatenate + minify) and dump each asset group, unless
106     // that was already done, in which case it should appear in
107     // drupal_css_cache_files.
108     // Drupal contrib can override this default CSS aggregator to keep the same
109     // grouping, optimizing and dumping, but change the strategy that is used to
110     // determine when the aggregate should be rebuilt (e.g. mtime, HTTPS …).
111     $css_assets = [];
112     $protocol_relative = $this->config->get('path.convert.absolute_to_protocol_relative');
113     $force_https = $this->config->get('path.convert.force_https');
114     $combine_media = $this->config->get('css.combine_media');
115     $page_uri = $this->requestStack->getCurrentRequest()->getUri();
116     foreach ($css_groups as $order => $css_group) {
117       // We have to return a single asset, not a group of assets. It is now up
118       // to one of the pieces of code in the switch statement below to set the
119       // 'data' property to the appropriate value.
120       $css_assets[$order] = $css_group;
121       unset($css_assets[$order]['items']);
122       switch ($css_group['type']) {
123         case 'file':
124           // No preprocessing, single CSS asset: just use the existing URI.
125           if (!$css_group['preprocess']) {
126             $css_assets[$order]['data'] = $css_group['items'][0]['data'];
127           }
128           // Preprocess (aggregate), unless the aggregate file already exists.
129           else {
130             $key = $this->generateHash($css_group) . $this->settingsHash;
131             $uri = '';
132             if ($aggregate = $this->advaggAggregates->get($key)) {
133               $uri = $aggregate['uri'];
134               $aggregate['basic']['pages'][] = $page_uri;
135               $this->advaggAggregates->set($key, $aggregate);
136             }
137             if (empty($uri) || !file_exists($uri)) {
138               // Optimize each asset within the group.
139               $data = '';
140               $group_file_info = $this->advaggFiles->getMultiple(array_column($css_group['items'], 'data'));
141
142               // Add aggregate & page to advaggFiles store per included file.
143               foreach ($group_file_info as &$file) {
144                 $file['aggregates'][] = $key;
145                 $file['pages'][] = $page_uri;
146               }
147               if (array_column($group_file_info, 'dns_prefetch')) {
148                 $css_assets[$order]['dns_prefetch'] = [];
149                 foreach ($group_file_info as $file) {
150                   if (!empty($file['dns_prefetch'])) {
151                     $css_assets[$order]['dns_prefetch'] = array_merge($css_assets[$order]['dns_prefetch'], $file['dns_prefetch']);
152                   }
153                 }
154               }
155               foreach ($css_group['items'] as $css_asset) {
156                 $content = $this->optimizer->optimize($css_asset);
157                 if ($combine_media && isset($css_asset['media']) && $css_asset['media'] != 'all') {
158                   $content = '@media ' . $css_asset['media'] . ' {' . $content . '}';
159                 }
160
161                 // Allow other modules to modify this file's contents.
162                 // Call hook_advagg_css_contents_alter().
163                 $this->moduleHandler->alter('advagg_css_contents', $content, $css_asset, $group_file_info);
164                 $data .= $content;
165               }
166               // Per the W3C specification at
167               // http://www.w3.org/TR/REC-CSS2/cascade.html#at-import, @import
168               // rules must precede any other style, so we move those to the
169               // top.
170               $regexp = '/@import[^;]+;/i';
171               preg_match_all($regexp, $data, $matches);
172               $data = preg_replace($regexp, '', $data);
173               $data = implode('', $matches[0]) . $data;
174               // Dump the optimized CSS for this group into an aggregate file.
175               list($uri, $filename) = $this->dumper->dump($data, 'css');
176               // Set the URI for this group's aggregate file.
177               $css_assets[$order]['data'] = $uri;
178               // Persist the URI for this aggregate file.
179               $aggregate_info = [
180                 'uri' => $uri,
181                 'uid' => $filename,
182                 'basic' => [
183                   'files' => array_keys($css_group['items']),
184                   'pages' => [$page_uri],
185                 ],
186                 'detailed' => [
187                   'files' => $css_group['items'],
188                   'hooks_hash' => advagg_current_hooks_hash_array(),
189                 ],
190               ];
191               $this->advaggAggregates->set($key, $aggregate_info);
192             }
193             else {
194               // Use the persisted URI for the optimized CSS file.
195               $css_assets[$order]['data'] = $uri;
196             }
197             $css_assets[$order]['preprocessed'] = TRUE;
198           }
199           break;
200
201         case 'external':
202           // We don't do any aggregation and hence also no caching for external
203           // CSS assets.
204           $uri = $css_group['items'][0]['data'];
205           if ($force_https) {
206             $uri = advagg_path_convert_force_https($uri);
207           }
208           elseif ($protocol_relative) {
209             $uri = advagg_path_convert_protocol_relative($uri);
210           }
211           $css_assets[$order]['data'] = $uri;
212           break;
213       }
214     }
215     return $css_assets;
216   }
217
218   /**
219    * Generate a hash for a given group of CSS assets.
220    *
221    * @param array $css_group
222    *   A group of CSS assets.
223    *
224    * @return string
225    *   A hash to uniquely identify the given group of CSS assets.
226    */
227   protected function generateHash(array $css_group) {
228     $css_data = [];
229     foreach ($css_group['items'] as $css_file) {
230       $css_data[] = $css_file['data'];
231       $css_data[] = filemtime($css_file['data']);
232     }
233     return hash('sha256', serialize($css_data));
234   }
235
236   /**
237    * Deletes all optimized collection assets.
238    *
239    * Note: Core's deleteAll() only deletes old files not all.
240    */
241   public function deleteAllReal() {
242     $log = [];
243     $this->state->delete('system.css_cache_files');
244     Cache::invalidateTags(['library_info']);
245     $delete_all = function ($uri) use (&$log) {
246       file_unmanaged_delete($uri);
247       $log[] = $uri;
248     };
249     $this->state->delete('system.js_cache_files');
250     file_scan_directory($this->dumper->preparePath('css'), '/.*/', ['callback' => $delete_all]);
251     return $log;
252   }
253
254   /**
255    * Delete stale optimized collection assets.
256    */
257   public function deleteStale() {
258     $log = [];
259     $this->state->delete('system.css_cache_files');
260     Cache::invalidateTags(['library_info']);
261     $delete_stale = function ($uri) use (&$log) {
262       // Default stale file threshold is 30 days.
263       if (REQUEST_TIME - fileatime($uri) > $this->systemConfig->get('stale_file_threshold')) {
264         file_unmanaged_delete($uri);
265         $log[] = $uri;
266       }
267     };
268     file_scan_directory($this->dumper->preparePath('css'), '/.*/', ['callback' => $delete_stale]);
269     return $log;
270   }
271
272   /**
273    * Delete old optimized collection assets.
274    */
275   public function deleteOld() {
276     $log = [];
277     $this->state->delete('system.css_cache_files');
278     Cache::invalidateTags(['library_info']);
279     $delete_old = function ($uri) use (&$log) {
280       // Default stale file threshold is 30 days.
281       // Delete old if > 3 times that.
282       if (REQUEST_TIME - filemtime($uri) > $this->systemConfig->get('stale_file_threshold') * 3) {
283         file_unmanaged_delete($uri);
284         $log[] = $uri;
285       }
286     };
287     file_scan_directory($this->dumper->preparePath('css'), '/.*/', ['callback' => $delete_old]);
288     return $log;
289   }
290
291 }