JsOptimizer.php 1.56 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Asset;

5
use Drupal\Component\Utility\Unicode;
6 7 8 9 10 11 12 13 14 15 16 17 18

/**
 * Optimizes a JavaScript asset.
 */
class JsOptimizer implements AssetOptimizerInterface {

  /**
   * {@inheritdoc}
   */
  public function optimize(array $js_asset) {
    if ($js_asset['type'] !== 'file') {
      throw new \Exception('Only file JavaScript assets can be optimized.');
    }
19
    if (!$js_asset['preprocess']) {
20 21 22
      throw new \Exception('Only file JavaScript assets with preprocessing enabled can be optimized.');
    }

23 24 25 26 27 28 29 30 31 32 33
    // If a BOM is found, convert the file to UTF-8, then use substr() to
    // remove the BOM from the result.
    $data = file_get_contents($js_asset['data']);
    if ($encoding = (Unicode::encodingFromBOM($data))) {
      $data = Unicode::substr(Unicode::convertToUtf8($data, $encoding), 1);
    }
    // If no BOM is found, check for the charset attribute.
    elseif (isset($js_asset['attributes']['charset'])) {
      $data = Unicode::convertToUtf8($data, $js_asset['attributes']['charset']);
    }

34
    // No-op optimizer: no optimizations are applied to JavaScript assets.
35
    return $data;
36 37
  }

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  /**
   * Processes the contents of a javascript asset for cleanup.
   *
   * @param string $contents
   *   The contents of the javascript asset.
   *
   * @return string
   *   Contents of the javascript asset.
   */
  public function clean($contents) {
    // Remove JS source and source mapping urls or these may cause 404 errors.
    $contents = preg_replace('/\/\/(#|@)\s(sourceURL|sourceMappingURL)=\s*(\S*?)\s*$/m', '', $contents);

    return $contents;
  }

54
}