CssCollectionOptimizer.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. <?php
  2. namespace Drupal\Core\Asset;
  3. use Drupal\Core\State\StateInterface;
  4. /**
  5. * Optimizes CSS assets.
  6. */
  7. class CssCollectionOptimizer implements AssetCollectionOptimizerInterface {
  8. /**
  9. * A CSS asset grouper.
  10. *
  11. * @var \Drupal\Core\Asset\CssCollectionGrouper
  12. */
  13. protected $grouper;
  14. /**
  15. * A CSS asset optimizer.
  16. *
  17. * @var \Drupal\Core\Asset\CssOptimizer
  18. */
  19. protected $optimizer;
  20. /**
  21. * An asset dumper.
  22. *
  23. * @var \Drupal\Core\Asset\AssetDumper
  24. */
  25. protected $dumper;
  26. /**
  27. * The state key/value store.
  28. *
  29. * @var \Drupal\Core\State\StateInterface
  30. */
  31. protected $state;
  32. /**
  33. * Constructs a CssCollectionOptimizer.
  34. *
  35. * @param \Drupal\Core\Asset\AssetCollectionGrouperInterface $grouper
  36. * The grouper for CSS assets.
  37. * @param \Drupal\Core\Asset\AssetOptimizerInterface $optimizer
  38. * The optimizer for a single CSS asset.
  39. * @param \Drupal\Core\Asset\AssetDumperInterface $dumper
  40. * The dumper for optimized CSS assets.
  41. * @param \Drupal\Core\State\StateInterface $state
  42. * The state key/value store.
  43. */
  44. public function __construct(AssetCollectionGrouperInterface $grouper, AssetOptimizerInterface $optimizer, AssetDumperInterface $dumper, StateInterface $state) {
  45. $this->grouper = $grouper;
  46. $this->optimizer = $optimizer;
  47. $this->dumper = $dumper;
  48. $this->state = $state;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. *
  53. * The cache file name is retrieved on a page load via a lookup variable that
  54. * contains an associative array. The array key is the hash of the file names
  55. * in $css while the value is the cache file name. The cache file is generated
  56. * in two cases. First, if there is no file name value for the key, which will
  57. * happen if a new file name has been added to $css or after the lookup
  58. * variable is emptied to force a rebuild of the cache. Second, the cache file
  59. * is generated if it is missing on disk. Old cache files are not deleted
  60. * immediately when the lookup variable is emptied, but are deleted after a
  61. * configurable period (@code system.performance.stale_file_threshold @endcode)
  62. * to ensure that files referenced by a cached page will still be available.
  63. */
  64. public function optimize(array $css_assets) {
  65. // Group the assets.
  66. $css_groups = $this->grouper->group($css_assets);
  67. // Now optimize (concatenate + minify) and dump each asset group, unless
  68. // that was already done, in which case it should appear in
  69. // drupal_css_cache_files.
  70. // Drupal contrib can override this default CSS aggregator to keep the same
  71. // grouping, optimizing and dumping, but change the strategy that is used to
  72. // determine when the aggregate should be rebuilt (e.g. mtime, HTTPS …).
  73. $map = $this->state->get('drupal_css_cache_files') ?: [];
  74. $css_assets = [];
  75. foreach ($css_groups as $order => $css_group) {
  76. // We have to return a single asset, not a group of assets. It is now up
  77. // to one of the pieces of code in the switch statement below to set the
  78. // 'data' property to the appropriate value.
  79. $css_assets[$order] = $css_group;
  80. unset($css_assets[$order]['items']);
  81. switch ($css_group['type']) {
  82. case 'file':
  83. // No preprocessing, single CSS asset: just use the existing URI.
  84. if (!$css_group['preprocess']) {
  85. $uri = $css_group['items'][0]['data'];
  86. $css_assets[$order]['data'] = $uri;
  87. }
  88. // Preprocess (aggregate), unless the aggregate file already exists.
  89. else {
  90. $key = $this->generateHash($css_group);
  91. $uri = '';
  92. if (isset($map[$key])) {
  93. $uri = $map[$key];
  94. }
  95. if (empty($uri) || !file_exists($uri)) {
  96. // Optimize each asset within the group.
  97. $data = '';
  98. foreach ($css_group['items'] as $css_asset) {
  99. $data .= $this->optimizer->optimize($css_asset);
  100. }
  101. // Per the W3C specification at
  102. // http://www.w3.org/TR/REC-CSS2/cascade.html#at-import, @import
  103. // rules must precede any other style, so we move those to the
  104. // top.
  105. $regexp = '/@import[^;]+;/i';
  106. preg_match_all($regexp, $data, $matches);
  107. $data = preg_replace($regexp, '', $data);
  108. $data = implode('', $matches[0]) . $data;
  109. // Dump the optimized CSS for this group into an aggregate file.
  110. $uri = $this->dumper->dump($data, 'css');
  111. // Set the URI for this group's aggregate file.
  112. $css_assets[$order]['data'] = $uri;
  113. // Persist the URI for this aggregate file.
  114. $map[$key] = $uri;
  115. $this->state->set('drupal_css_cache_files', $map);
  116. }
  117. else {
  118. // Use the persisted URI for the optimized CSS file.
  119. $css_assets[$order]['data'] = $uri;
  120. }
  121. $css_assets[$order]['preprocessed'] = TRUE;
  122. }
  123. break;
  124. case 'external':
  125. // We don't do any aggregation and hence also no caching for external
  126. // CSS assets.
  127. $uri = $css_group['items'][0]['data'];
  128. $css_assets[$order]['data'] = $uri;
  129. break;
  130. }
  131. }
  132. return $css_assets;
  133. }
  134. /**
  135. * Generate a hash for a given group of CSS assets.
  136. *
  137. * @param array $css_group
  138. * A group of CSS assets.
  139. *
  140. * @return string
  141. * A hash to uniquely identify the given group of CSS assets.
  142. */
  143. protected function generateHash(array $css_group) {
  144. $css_data = [];
  145. foreach ($css_group['items'] as $css_file) {
  146. $css_data[] = $css_file['data'];
  147. }
  148. return hash('sha256', serialize($css_data));
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function getAll() {
  154. return $this->state->get('drupal_css_cache_files');
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. public function deleteAll() {
  160. $this->state->delete('drupal_css_cache_files');
  161. $delete_stale = function ($uri) {
  162. // Default stale file threshold is 30 days.
  163. if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) {
  164. file_unmanaged_delete($uri);
  165. }
  166. };
  167. file_scan_directory('public://css', '/.*/', ['callback' => $delete_stale]);
  168. }
  169. }