JsCollectionRenderer.php in Advanced CSS/JS Aggregation 8.2
File
src/Asset/JsCollectionRenderer.php
View source
<?php
namespace Drupal\advagg\Asset;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Asset\AssetCollectionRendererInterface;
use Drupal\Core\Asset\JsCollectionRenderer as CoreJsCollectionRenderer;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\State\StateInterface;
class JsCollectionRenderer extends CoreJsCollectionRenderer implements AssetCollectionRendererInterface {
protected $config;
public function __construct(StateInterface $state, ConfigFactoryInterface $config_factory) {
$this->state = $state;
$this->config = $config_factory
->get('advagg.settings');
}
public function render(array $js_assets) {
if (isset($js_assets['-1']) && empty($js_assets[-1])) {
unset($js_assets['-1']);
}
$elements = [
'prefetch' => [],
];
$prefetch = $this->config
->get('dns_prefetch');
$default_query_string = $this->state
->get('system.css_js_query_string') ?: '0';
$element_defaults = [
'#type' => 'html_tag',
'#tag' => 'script',
'#value' => '',
];
$prefetch_element_defaults = [
'#type' => 'html_tag',
'#tag' => 'link',
'#attributes' => [
'rel' => 'dns-prefetch',
],
];
foreach ($js_assets as $js_asset) {
$element = $element_defaults;
$element['#browsers'] = $js_asset['browsers'];
switch ($js_asset['type']) {
case 'setting':
$element['#attributes'] = [
'type' => 'application/json',
'data-drupal-selector' => 'drupal-settings-json',
];
$element['#value'] = Json::encode($js_asset['data']);
break;
case 'file':
$query_string = $js_asset['version'] == -1 ? $default_query_string : 'v=' . $js_asset['version'];
$query_string_separator = strpos($js_asset['data'], '?') !== FALSE ? '&' : '?';
$element['#attributes']['src'] = file_url_transform_relative(file_create_url($js_asset['data']));
if (!isset($js_asset['preprocessed'])) {
$element['#attributes']['src'] .= $query_string_separator . ($js_asset['cache'] ? $query_string : REQUEST_TIME);
}
$element['#inline'] = !empty($js_asset['inline']) ? TRUE : FALSE;
break;
case 'external':
$element['#attributes']['src'] = $js_asset['data'];
if ($prefetch) {
$pre_element = $prefetch_element_defaults;
$pre_element['#attributes']['href'] = '//' . parse_url($js_asset['data'], PHP_URL_HOST);
$elements['prefetch'][] = $pre_element;
}
break;
default:
throw new \Exception('Invalid JS asset type.');
}
if (!empty($element['#attributes']['src']) && !empty($js_asset['attributes'])) {
$element['#attributes'] += $js_asset['attributes'];
}
$elements[] = $element;
}
if (empty($elements['prefetch'])) {
unset($elements['prefetch']);
}
return $elements;
}
}