JsOptimizer.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Drupal\Core\Asset;
  3. use Drupal\Component\Utility\Unicode;
  4. /**
  5. * Optimizes a JavaScript asset.
  6. */
  7. class JsOptimizer implements AssetOptimizerInterface {
  8. /**
  9. * {@inheritdoc}
  10. */
  11. public function optimize(array $js_asset) {
  12. if ($js_asset['type'] !== 'file') {
  13. throw new \Exception('Only file JavaScript assets can be optimized.');
  14. }
  15. if (!$js_asset['preprocess']) {
  16. throw new \Exception('Only file JavaScript assets with preprocessing enabled can be optimized.');
  17. }
  18. // If a BOM is found, convert the file to UTF-8, then use substr() to
  19. // remove the BOM from the result.
  20. $data = file_get_contents($js_asset['data']);
  21. if ($encoding = (Unicode::encodingFromBOM($data))) {
  22. $data = mb_substr(Unicode::convertToUtf8($data, $encoding), 1);
  23. }
  24. // If no BOM is found, check for the charset attribute.
  25. elseif (isset($js_asset['attributes']['charset'])) {
  26. $data = Unicode::convertToUtf8($data, $js_asset['attributes']['charset']);
  27. }
  28. // No-op optimizer: no optimizations are applied to JavaScript assets.
  29. return $data;
  30. }
  31. /**
  32. * Processes the contents of a javascript asset for cleanup.
  33. *
  34. * @param string $contents
  35. * The contents of the javascript asset.
  36. *
  37. * @return string
  38. * Contents of the javascript asset.
  39. */
  40. public function clean($contents) {
  41. // Remove JS source and source mapping urls or these may cause 404 errors.
  42. $contents = preg_replace('/\/\/(#|@)\s(sourceURL|sourceMappingURL)=\s*(\S*?)\s*$/m', '', $contents);
  43. return $contents;
  44. }
  45. }