3 namespace Drupal\Core\Asset;
5 use Drupal\Core\State\StateInterface;
9 * Optimizes JavaScript assets.
11 class JsCollectionOptimizer implements AssetCollectionOptimizerInterface {
16 * @var \Drupal\Core\Asset\JsCollectionGrouper
21 * A JS asset optimizer.
23 * @var \Drupal\Core\Asset\JsOptimizer
30 * @var \Drupal\Core\Asset\AssetDumper
35 * The state key/value store.
37 * @var \Drupal\Core\State\StateInterface
42 * Constructs a JsCollectionOptimizer.
44 * @param \Drupal\Core\Asset\AssetCollectionGrouperInterface $grouper
45 * The grouper for JS assets.
46 * @param \Drupal\Core\Asset\AssetOptimizerInterface $optimizer
47 * The optimizer for a single JS asset.
48 * @param \Drupal\Core\Asset\AssetDumperInterface $dumper
49 * The dumper for optimized JS assets.
50 * @param \Drupal\Core\State\StateInterface $state
51 * The state key/value store.
53 public function __construct(AssetCollectionGrouperInterface $grouper, AssetOptimizerInterface $optimizer, AssetDumperInterface $dumper, StateInterface $state) {
54 $this->grouper = $grouper;
55 $this->optimizer = $optimizer;
56 $this->dumper = $dumper;
57 $this->state = $state;
63 * The cache file name is retrieved on a page load via a lookup variable that
64 * contains an associative array. The array key is the hash of the names in
65 * $files while the value is the cache file name. The cache file is generated
66 * in two cases. First, if there is no file name value for the key, which will
67 * happen if a new file name has been added to $files or after the lookup
68 * variable is emptied to force a rebuild of the cache. Second, the cache file
69 * is generated if it is missing on disk. Old cache files are not deleted
70 * immediately when the lookup variable is emptied, but are deleted after a
71 * configurable period (@code system.performance.stale_file_threshold @endcode)
72 * to ensure that files referenced by a cached page will still be available.
74 public function optimize(array $js_assets) {
76 $js_groups = $this->grouper->group($js_assets);
78 // Now optimize (concatenate, not minify) and dump each asset group, unless
79 // that was already done, in which case it should appear in
80 // system.js_cache_files.
81 // Drupal contrib can override this default JS aggregator to keep the same
82 // grouping, optimizing and dumping, but change the strategy that is used to
83 // determine when the aggregate should be rebuilt (e.g. mtime, HTTPS …).
84 $map = $this->state->get('system.js_cache_files') ?: [];
86 foreach ($js_groups as $order => $js_group) {
87 // We have to return a single asset, not a group of assets. It is now up
88 // to one of the pieces of code in the switch statement below to set the
89 // 'data' property to the appropriate value.
90 $js_assets[$order] = $js_group;
91 unset($js_assets[$order]['items']);
93 switch ($js_group['type']) {
95 // No preprocessing, single JS asset: just use the existing URI.
96 if (!$js_group['preprocess']) {
97 $uri = $js_group['items'][0]['data'];
98 $js_assets[$order]['data'] = $uri;
100 // Preprocess (aggregate), unless the aggregate file already exists.
102 $key = $this->generateHash($js_group);
104 if (isset($map[$key])) {
107 if (empty($uri) || !file_exists($uri)) {
108 // Concatenate each asset within the group.
110 foreach ($js_group['items'] as $js_asset) {
111 // Optimize this JS file, but only if it's not yet minified.
112 if (isset($js_asset['minified']) && $js_asset['minified']) {
113 $data .= file_get_contents($js_asset['data']);
116 $data .= $this->optimizer->optimize($js_asset);
118 // Append a ';' and a newline after each JS file to prevent them
119 // from running together.
122 // Remove unwanted JS code that cause issues.
123 $data = $this->optimizer->clean($data);
124 // Dump the optimized JS for this group into an aggregate file.
125 $uri = $this->dumper->dump($data, 'js');
126 // Set the URI for this group's aggregate file.
127 $js_assets[$order]['data'] = $uri;
128 // Persist the URI for this aggregate file.
130 $this->state->set('system.js_cache_files', $map);
133 // Use the persisted URI for the optimized JS file.
134 $js_assets[$order]['data'] = $uri;
136 $js_assets[$order]['preprocessed'] = TRUE;
141 // We don't do any aggregation and hence also no caching for external
143 $uri = $js_group['items'][0]['data'];
144 $js_assets[$order]['data'] = $uri;
153 * Generate a hash for a given group of JavaScript assets.
155 * @param array $js_group
156 * A group of JavaScript assets.
159 * A hash to uniquely identify the given group of JavaScript assets.
161 protected function generateHash(array $js_group) {
163 foreach ($js_group['items'] as $js_file) {
164 $js_data[] = $js_file['data'];
166 return hash('sha256', serialize($js_data));
172 public function getAll() {
173 return $this->state->get('system.js_cache_files');
179 public function deleteAll() {
180 $this->state->delete('system.js_cache_files');
181 $delete_stale = function($uri) {
182 // Default stale file threshold is 30 days.
183 if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) {
184 file_unmanaged_delete($uri);
187 file_scan_directory('public://js', '/.*/', ['callback' => $delete_stale]);