View source  
  <?php
namespace Drupal\advagg_js_minify\Asset;
use Drupal\Component\Utility\Unicode;
use Drupal\advagg\Asset\SingleAssetOptimizerBase;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Psr\Log\LoggerInterface;
class JsMinifier extends SingleAssetOptimizerBase {
  use StringTranslationTrait;
  
  public function __construct(LoggerInterface $logger, ConfigFactoryInterface $config_factory) {
    parent::__construct($logger);
    $this->config = $config_factory
      ->get('advagg_js_minify.settings');
  }
  
  public function optimize($contents, array $asset, array $data) {
    
    if (!($minifier = $this->config
      ->get('minifier'))) {
      return $contents;
    }
    
    if ($this
      ->isMinified($contents)) {
      return $contents;
    }
    $this
      ->clean($contents, $asset);
    $contents_original = $contents;
    $function = $this
      ->getFunction($minifier);
    if (!is_callable($function)) {
      return $contents;
    }
    $arguments = [
      &$contents,
      $asset['data'],
    ];
    call_user_func_array($function, $arguments);
    $contents = trim($contents);
    
    if (strpbrk(substr(trim($contents), -1), ';})') === FALSE) {
      $contents .= ';';
    }
    if (!$this
      ->isMinificationSuccess($contents, $contents_original)) {
      return $contents_original;
    }
    return $contents;
  }
  
  protected function getFunction($minifier) {
    $functions = [
      1 => [
        $this,
        'minifyJsminplus',
      ],
      2 => [
        $this,
        'minifyJspacker',
      ],
      3 => [
        $this,
        'minifyJsmin',
      ],
      4 => [
        $this,
        'minifyJshrink',
      ],
      5 => [
        $this,
        'minifyJsqueeze',
      ],
    ];
    return $functions[$minifier];
  }
  
  public function clean($contents, array $asset) {
    if ($encoding = Unicode::encodingFromBOM($contents)) {
      $contents = mb_substr(Unicode::convertToUtf8($contents, $encoding), 1);
    }
    elseif (isset($asset['attributes']['charset'])) {
      $contents = Unicode::convertToUtf8($contents, $asset['attributes']['charset']);
    }
    
    $contents = preg_replace('/\\/\\/(#|@)\\s(sourceURL|sourceMappingURL)=\\s*(\\S*?)\\s*$/m', '', $contents);
    return $contents;
  }
  
  public function minifyJsmin(&$contents, $path) {
    
    if (!function_exists('jsmin')) {
      $this->logger
        ->notice($this
        ->t('The jsmin function does not exist. Using JSqueeze.'), []);
      $contents = $this
        ->minifyJsqueeze($contents);
      return;
    }
    
    if (version_compare(phpversion('jsmin'), '2.0.0', '<') && $this
      ->stringContainsMultibyteCharacters($contents)) {
      $this->logger
        ->notice('The currently installed jsmin version does not handle multibyte characters, you may consider to upgrade the jsmin extension. Using JSqueeze fallback.', []);
      $contents = $this
        ->minifyJsqueeze($contents);
      return;
    }
    
    $contents = str_replace("\t", " ", $contents);
    $minified = jsmin($contents);
    
    $error = jsmin_last_error_msg();
    if ($error != 'No error') {
      $this->logger
        ->warning('JSMin had an error processing, using JSqueeze fallback. Error details: ' . $error, []);
      $contents = $this
        ->minifyJsqueeze($contents);
      return;
    }
    
    if (ctype_cntrl(substr(trim($minified), -1)) || strpbrk(substr(trim($minified), -1), ';})') === FALSE) {
      $this->logger
        ->notice($this
        ->t('JSMin had a possible error minifying: @file, correcting.', [
        '@file' => $path,
      ]));
      if (strrpos(substr($minified, -10), ';')) {
        $contents = substr($minified, 0, strrpos($minified, ';'));
      }
    }
    else {
      $contents = $minified;
    }
    $semicolons = substr_count($contents, ';', strlen($contents) - 5);
    if ($semicolons > 2) {
      $start = substr($contents, 0, -5);
      $contents = $start . preg_replace("/([;)}]*)([\\w]*)([;)}]*)/", "\$1\$3", substr($contents, -5));
      $this->logger
        ->notice($this
        ->t('JSMin had an error minifying file: @file, attempting to correct.', [
        '@file' => $path,
      ]));
    }
  }
  
  public function minifyJsminplus(&$contents) {
    $contents_before = $contents;
    
    if (!class_exists('\\JSMinPlus')) {
      include drupal_get_path('module', 'advagg_js_minify') . '/jsminplus.inc';
      $nesting_level = ini_get('xdebug.max_nesting_level');
      if (!empty($nesting_level) && $nesting_level < 200) {
        ini_set('xdebug.max_nesting_level', 200);
      }
    }
    ob_start();
    try {
      
      $contents = \JSMinPlus::minify($contents);
      
      $error = trim(ob_get_contents());
      if (!empty($error)) {
        throw new \Exception($error);
      }
    } catch (\Exception $e) {
      
      $this->logger
        ->warning($e
        ->getMessage(), []);
      $contents = $contents_before;
    }
    ob_end_clean();
  }
  
  public function minifyJspacker(&$contents) {
    
    if (!class_exists('\\JavaScriptPacker')) {
      include drupal_get_path('module', 'advagg_js_minify') . '/jspacker.inc';
    }
    
    $contents = str_replace("}\n", "};\n", $contents);
    $contents = str_replace("\nfunction", ";\nfunction", $contents);
    $packer = new \JavaScriptPacker($contents, 62, TRUE, FALSE);
    $contents = $packer
      ->pack();
  }
  
  public function minifyJshrink(&$contents) {
    $contents_before = $contents;
    
    if (!class_exists('\\JShrink\\Minifier')) {
      include drupal_get_path('module', 'advagg_js_minify') . '/jshrink.inc';
      $nesting_level = ini_get('xdebug.max_nesting_level');
      if (!empty($nesting_level) && $nesting_level < 200) {
        ini_set('xdebug.max_nesting_level', 200);
      }
    }
    ob_start();
    try {
      
      $contents = \JShrink\Minifier::minify($contents, [
        'flaggedComments' => FALSE,
      ]);
      
      $error = trim(ob_get_contents());
      if (!empty($error)) {
        throw new \Exception($error);
      }
    } catch (\Exception $e) {
      
      $this->logger
        ->warning($e
        ->getMessage(), []);
      $contents = $contents_before;
    }
    ob_end_clean();
  }
  
  public function minifyJsqueeze(&$contents) {
    $contents_before = $contents;
    
    if (!class_exists('\\Patchwork\\JSqueeze')) {
      include drupal_get_path('module', 'advagg_js_minify') . '/jsqueeze.inc';
      $nesting_level = ini_get('xdebug.max_nesting_level');
      if (!empty($nesting_level) && $nesting_level < 200) {
        ini_set('xdebug.max_nesting_level', 200);
      }
    }
    ob_start();
    try {
      
      $jz = new \Patchwork\JSqueeze();
      $contents = $jz
        ->squeeze($contents, TRUE, $this->config
        ->get('add_license'), FALSE);
      
      $error = trim(ob_get_contents());
      if (!empty($error)) {
        throw new \Exception($error);
      }
    } catch (\Exception $e) {
      
      $this->logger
        ->warning('JSqueeze error, skipping file. ' . $e
        ->getMessage(), []);
      $contents = $contents_before;
    }
    ob_end_clean();
  }
}