CssCollectionOptimizer.php 6.9 KB

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