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