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\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;
19 class CssCollectionOptimizer extends CoreCssCollectionOptimizer implements AssetCollectionOptimizerInterface {
22 * A config object for the advagg configuration.
24 * @var \Drupal\Core\Config\Config
29 * A config object for the system performance configuration.
31 * @var \Drupal\Core\Config\Config
33 protected $systemConfig;
36 * A state information store for the AdvAgg generated aggregates.
38 * @var \Drupal\Core\State\StateInterface
40 protected $advaggAggregates;
43 * Module handler service.
45 * @var \Drupal\Core\Extension\ModuleHandlerInterface
47 protected $moduleHandler;
50 * The AdvAgg file status state information storage service.
52 * @var \Drupal\Core\State\StateInterface
54 protected $advaggFiles;
57 * Hash of the AdvAgg settings.
61 protected $settingsHash;
66 * @var \Symfony\Component\HttpFoundation\RequestStack
68 protected $requestStack;
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
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
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;
101 public function optimize(array $css_assets) {
103 $css_groups = $this->grouper->group($css_assets);
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 …).
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']) {
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'];
128 // Preprocess (aggregate), unless the aggregate file already exists.
130 $key = $this->generateHash($css_group) . $this->settingsHash;
132 if ($aggregate = $this->advaggAggregates->get($key)) {
133 $uri = $aggregate['uri'];
134 $aggregate['basic']['pages'][] = $page_uri;
135 $this->advaggAggregates->set($key, $aggregate);
137 if (empty($uri) || !file_exists($uri)) {
138 // Optimize each asset within the group.
140 $group_file_info = $this->advaggFiles->getMultiple(array_column($css_group['items'], 'data'));
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;
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']);
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 . '}';
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);
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
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.
183 'files' => array_keys($css_group['items']),
184 'pages' => [$page_uri],
187 'files' => $css_group['items'],
188 'hooks_hash' => advagg_current_hooks_hash_array(),
191 $this->advaggAggregates->set($key, $aggregate_info);
194 // Use the persisted URI for the optimized CSS file.
195 $css_assets[$order]['data'] = $uri;
197 $css_assets[$order]['preprocessed'] = TRUE;
202 // We don't do any aggregation and hence also no caching for external
204 $uri = $css_group['items'][0]['data'];
206 $uri = advagg_path_convert_force_https($uri);
208 elseif ($protocol_relative) {
209 $uri = advagg_path_convert_protocol_relative($uri);
211 $css_assets[$order]['data'] = $uri;
219 * Generate a hash for a given group of CSS assets.
221 * @param array $css_group
222 * A group of CSS assets.
225 * A hash to uniquely identify the given group of CSS assets.
227 protected function generateHash(array $css_group) {
229 foreach ($css_group['items'] as $css_file) {
230 $css_data[] = $css_file['data'];
231 $css_data[] = filemtime($css_file['data']);
233 return hash('sha256', serialize($css_data));
237 * Deletes all optimized collection assets.
239 * Note: Core's deleteAll() only deletes old files not all.
241 public function deleteAllReal() {
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);
249 $this->state->delete('system.js_cache_files');
250 file_scan_directory($this->dumper->preparePath('css'), '/.*/', ['callback' => $delete_all]);
255 * Delete stale optimized collection assets.
257 public function deleteStale() {
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);
268 file_scan_directory($this->dumper->preparePath('css'), '/.*/', ['callback' => $delete_stale]);
273 * Delete old optimized collection assets.
275 public function deleteOld() {
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);
287 file_scan_directory($this->dumper->preparePath('css'), '/.*/', ['callback' => $delete_old]);