annotate core/lib/Drupal/Core/Asset/JsOptimizer.php @ 19:fa3358dc1485 tip

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