JsOptimizer.php in Advanced CSS/JS Aggregation 8.3
File
src/Asset/JsOptimizer.php
View source
<?php
namespace Drupal\advagg\Asset;
use Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
class JsOptimizer extends AssetOptimizer {
public function __construct(ConfigFactoryInterface $config_factory, ContainerAwareEventDispatcher $event_dispatcher, CacheBackendInterface $cache) {
$this->extension = 'js';
parent::__construct($config_factory, $event_dispatcher, $cache);
}
protected function addDnsPrefetch(array $asset) {
$prefetch = $this
->testForGoogleAdManager($asset['data']);
$prefetch += $this
->testForGoogleAnalytics($asset['data']);
return $prefetch;
}
protected function fixType(array &$asset) {
if (!in_array($asset['type'], [
'file',
'external',
'settings',
])) {
$asset['type'] = 'file';
}
$path = $asset['data'];
if ($asset['type'] === 'external') {
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';
}
}
private function testForGoogleAdManager($path) {
$prefetch = [];
if (strpos($path, '/google_service.') == FALSE) {
return $prefetch;
}
$prefetch[] = 'https://csi.gstatic.com';
$prefetch[] = 'https://pubads.g.doubleclick.net';
$prefetch[] = 'https://partner.googleadservices.com';
$prefetch[] = 'https://securepubads.g.doubleclick.net';
$prefetch[] = 'https://pagead2.googlesyndication.com';
$prefetch[] = 'https://cm.g.doubleclick.net';
$prefetch[] = 'https://tpc.googlesyndication.com';
return $prefetch;
}
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;
}
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 ($contents === $data['contents'] && !$this->gZip) {
return FALSE;
}
return $this
->writeFile($contents, $data['cid']);
}
}