Same name and namespace in other branches
  1. 6.0.x src/Asset/JsOptimizer.php \Drupal\advagg\Asset\JsOptimizer 1 comment
  2. 8.x-2.x advagg_js_minify/src/Asset/JsOptimizer.php \Drupal\advagg_js_minify\Asset\JsOptimizer 1 comment
  3. 8.x-3.x src/Asset/JsOptimizer.php \Drupal\advagg\Asset\JsOptimizer 1 comment
  4. 8.x-4.x src/Asset/JsOptimizer.php \Drupal\advagg\Asset\JsOptimizer 1 comment

The JavaScript Optimizer.

Hierarchy

Expanded class hierarchy of JsOptimizer

1 string reference to 'JsOptimizer'
advagg.services.yml in ./advagg.services.yml
advagg.services.yml
1 service uses JsOptimizer
advagg.optimizer.js in ./advagg.services.yml
Drupal\advagg\Asset\JsOptimizer

File

src/Asset/JsOptimizer.php, line 12

Namespace

Drupal\advagg\Asset
View source
class JsOptimizer extends AssetOptimizer {
    
    /**
     * {@inheritdoc}
     */
    public function __construct(ConfigFactoryInterface $config_factory, ContainerAwareEventDispatcher $event_dispatcher, CacheBackendInterface $cache) {
        $this->extension = 'js';
        parent::__construct($config_factory, $event_dispatcher, $cache);
    }
    
    /**
     * {@inheritdoc}
     */
    protected function addDnsPrefetch(array $asset) {
        // Check if Google Ad Manager and add DNS prefetch.
        $prefetch = $this->testForGoogleAdManager($asset['data']);
        // Check if Google Analytics and add DNS prefetch.
        $prefetch += $this->testForGoogleAnalytics($asset['data']);
        return $prefetch;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function fixType(array &$asset) {
        // Default asset type to file if not set/invalid.
        if (!in_array($asset['type'], [
            'file',
            'external',
            'settings',
        ])) {
            $asset['type'] = 'file';
        }
        $path = $asset['data'];
        if ($asset['type'] === 'external') {
            // If type is external but path doesn't start with http, https, or //
            // change it to file.
            if (stripos($path, 'http') !== 0 && stripos($path, '//') !== 0) {
                $asset['type'] = 'file';
            }
            elseif (stripos($path, $this->basePath) !== FALSE && !$this->config
                ->get('js.preserve_external')) {
                $asset['type'] = 'file';
                $asset['group'] = JS_LIBRARY;
                $asset['every_page'] = TRUE;
                $asset['weight'] = -40000;
                $asset['data'] = substr($asset['data'], stripos($asset['data'], $this->basePath) + $this->basePathLen);
            }
        }
        elseif ($asset['type'] === 'file' && (stripos($path, 'http') === 0 || stripos($path, '//') === 0)) {
            $asset['type'] = 'external';
        }
    }
    
    /**
     * Test if the provided path is from Google Ad Manager and add DNS entries.
     *
     * @param string $path
     *   The path to check.
     *
     * @return array
     *   Array of prefetch domains if file is from Google Ad Manager.
     */
    private function testForGoogleAdManager($path) {
        $prefetch = [];
        if (strpos($path, '/google_service.') == FALSE) {
            return $prefetch;
        }
        // Domains in the google_service.js file.
        $prefetch[] = 'https://csi.gstatic.com';
        $prefetch[] = 'https://pubads.g.doubleclick.net';
        $prefetch[] = 'https://partner.googleadservices.com';
        $prefetch[] = 'https://securepubads.g.doubleclick.net';
        // Domains in the google_ads.js file.
        $prefetch[] = 'https://pagead2.googlesyndication.com';
        // Other domains that usually get hit.
        $prefetch[] = 'https://cm.g.doubleclick.net';
        $prefetch[] = 'https://tpc.googlesyndication.com';
        return $prefetch;
    }
    
    /**
     * Test if the provided path is from Google Analytics and add DNS entries.
     *
     * @param string $path
     *   The path to check.
     *
     * @return array
     *   Empty array or an array to prefetch if file is from Google Analytics.
     */
    private function testForGoogleAnalytics($path) {
        $prefetch = [];
        if (strpos($path, 'GoogleAnalytics') == FALSE && strpos($path, 'google-analytics') == FALSE) {
            return $prefetch;
        }
        $prefetch[] = 'https://ssl.google-analytics.com';
        $prefetch[] = 'https://stats.g.doubleclick.net';
        return $prefetch;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function optimizeFile(array &$asset, array $data) {
        $asset_event = new AssetOptimizationEvent($data['contents'], $asset, $data);
        $this->eventDispatcher
            ->dispatch(AssetOptimizationEvent::JS, $asset_event);
        $contents = $asset_event->getContent();
        $asset = $asset_event->getAsset();
        // If file contents are unaltered return FALSE.
        if ($contents === $data['contents'] && !$this->gZip) {
            return FALSE;
        }
        return $this->writeFile($contents, $data['cid']);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
AssetOptimizer::$basePath protected property The base path.
AssetOptimizer::$basePathLen protected property The base path length.
AssetOptimizer::$brotli protected property Whether or not to brotli compress assets.
AssetOptimizer::$cache protected property The AdvAgg cache.
AssetOptimizer::$cacheLevel protected property Config level of caching of assets.
AssetOptimizer::$cacheTime protected property The cache time.
AssetOptimizer::$config protected property A config object for the advagg configuration.
AssetOptimizer::$dnsPrefetch protected property Array of domains to prefetch. Copied to $GLOBALS for later use.
AssetOptimizer::$eventDispatcher protected property Event Dispatcher service.
AssetOptimizer::$extension protected property Asset type (css or js).
AssetOptimizer::$fileSystem protected property The file system.
AssetOptimizer::$fixType protected property Config to control fixing the asset type (file, external). 2
AssetOptimizer::$gZip protected property Whether or not to gzip assets.
AssetOptimizer::convertPathForceHttps protected function Convert http:// to https://.
AssetOptimizer::convertPathProtocolRelative protected function Converts absolute paths to be protocol relative paths.
AssetOptimizer::generateHtaccess public static function Generate an htaccess file in the optimized asset dirs to improve serving.
AssetOptimizer::getCacheTime protected function Get how long to cache an asset. Varies on cache level setting.
AssetOptimizer::processAssetArray public function Process a core asset array.
AssetOptimizer::scanFile protected function Given a filename calculate various hashes, gather meta data then optimize.
AssetOptimizer::shouldBrotli protected function Determine if settings and available PHP modules allow brotli-ing assets.
AssetOptimizer::shouldGZip protected function Determine if settings and available PHP modules allow GZipping assets.
AssetOptimizer::sortStable public static function Stable sort for CSS and JS items.
AssetOptimizer::writeFile protected function The filename for the CSS or JS optimized file is the cid.
JsOptimizer::addDnsPrefetch protected function Extract any domains to prefetch DNS. Overrides AssetOptimizer::addDnsPrefetch
JsOptimizer::fixType protected function Checks for and if found fixes incorrectly set asset types. Overrides AssetOptimizer::fixType
JsOptimizer::optimizeFile protected function Perform any in-place optimization & pass to event for further optimization. Overrides AssetOptimizer::optimizeFile
JsOptimizer::testForGoogleAdManager private function Test if the provided path is from Google Ad Manager and add DNS entries.
JsOptimizer::testForGoogleAnalytics private function Test if the provided path is from Google Analytics and add DNS entries.
JsOptimizer::__construct public function Constructs the Optimizer object. Overrides AssetOptimizer::__construct