PageRenderTime 25ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/core/lib/Drupal/Core/Asset/JsCollectionOptimizer.php

https://gitlab.com/reasonat/test8
PHP | 190 lines | 84 code | 18 blank | 88 comment | 11 complexity | 135936c20abb8a0c3ae9d873aab0799b MD5 | raw file
  1. <?php
  2. namespace Drupal\Core\Asset;
  3. use Drupal\Core\State\StateInterface;
  4. /**
  5. * Optimizes JavaScript assets.
  6. */
  7. class JsCollectionOptimizer implements AssetCollectionOptimizerInterface {
  8. /**
  9. * A JS asset grouper.
  10. *
  11. * @var \Drupal\Core\Asset\JsCollectionGrouper
  12. */
  13. protected $grouper;
  14. /**
  15. * A JS asset optimizer.
  16. *
  17. * @var \Drupal\Core\Asset\JsOptimizer
  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 JsCollectionOptimizer.
  34. *
  35. * @param \Drupal\Core\Asset\AssetCollectionGrouperInterface
  36. * The grouper for JS assets.
  37. * @param \Drupal\Core\Asset\AssetOptimizerInterface
  38. * The optimizer for a single JS asset.
  39. * @param \Drupal\Core\Asset\AssetDumperInterface
  40. * The dumper for optimized JS assets.
  41. * @param \Drupal\Core\State\StateInterface
  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 names in
  55. * $files 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 $files 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 $js_assets) {
  65. // Group the assets.
  66. $js_groups = $this->grouper->group($js_assets);
  67. // Now optimize (concatenate, not minify) and dump each asset group, unless
  68. // that was already done, in which case it should appear in
  69. // system.js_cache_files.
  70. // Drupal contrib can override this default JS 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('system.js_cache_files') ?: array();
  74. $js_assets = array();
  75. foreach ($js_groups as $order => $js_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. $js_assets[$order] = $js_group;
  80. unset($js_assets[$order]['items']);
  81. switch ($js_group['type']) {
  82. case 'file':
  83. // No preprocessing, single JS asset: just use the existing URI.
  84. if (!$js_group['preprocess']) {
  85. $uri = $js_group['items'][0]['data'];
  86. $js_assets[$order]['data'] = $uri;
  87. }
  88. // Preprocess (aggregate), unless the aggregate file already exists.
  89. else {
  90. $key = $this->generateHash($js_group);
  91. $uri = '';
  92. if (isset($map[$key])) {
  93. $uri = $map[$key];
  94. }
  95. if (empty($uri) || !file_exists($uri)) {
  96. // Concatenate each asset within the group.
  97. $data = '';
  98. foreach ($js_group['items'] as $js_asset) {
  99. // Optimize this JS file, but only if it's not yet minified.
  100. if (isset($js_asset['minified']) && $js_asset['minified']) {
  101. $data .= file_get_contents($js_asset['data']);
  102. }
  103. else {
  104. $data .= $this->optimizer->optimize($js_asset);
  105. }
  106. // Append a ';' and a newline after each JS file to prevent them
  107. // from running together.
  108. $data .= ";\n";
  109. }
  110. // Remove unwanted JS code that cause issues.
  111. $data = $this->optimizer->clean($data);
  112. // Dump the optimized JS for this group into an aggregate file.
  113. $uri = $this->dumper->dump($data, 'js');
  114. // Set the URI for this group's aggregate file.
  115. $js_assets[$order]['data'] = $uri;
  116. // Persist the URI for this aggregate file.
  117. $map[$key] = $uri;
  118. $this->state->set('system.js_cache_files', $map);
  119. }
  120. else {
  121. // Use the persisted URI for the optimized JS file.
  122. $js_assets[$order]['data'] = $uri;
  123. }
  124. $js_assets[$order]['preprocessed'] = TRUE;
  125. }
  126. break;
  127. case 'external':
  128. // We don't do any aggregation and hence also no caching for external
  129. // JS assets.
  130. $uri = $js_group['items'][0]['data'];
  131. $js_assets[$order]['data'] = $uri;
  132. break;
  133. }
  134. }
  135. return $js_assets;
  136. }
  137. /**
  138. * Generate a hash for a given group of JavaScript assets.
  139. *
  140. * @param array $js_group
  141. * A group of JavaScript assets.
  142. *
  143. * @return string
  144. * A hash to uniquely identify the given group of JavaScript assets.
  145. */
  146. protected function generateHash(array $js_group) {
  147. $js_data = array();
  148. foreach ($js_group['items'] as $js_file) {
  149. $js_data[] = $js_file['data'];
  150. }
  151. return hash('sha256', serialize($js_data));
  152. }
  153. /**
  154. * {@inheritdoc}
  155. */
  156. public function getAll() {
  157. return $this->state->get('system.js_cache_files');
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function deleteAll() {
  163. $this->state->delete('system.js_cache_files');
  164. $delete_stale = function($uri) {
  165. // Default stale file threshold is 30 days.
  166. if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) {
  167. file_unmanaged_delete($uri);
  168. }
  169. };
  170. file_scan_directory('public://js', '/.*/', array('callback' => $delete_stale));
  171. }
  172. }