ResponseSubscriber.php in Advanced CSS/JS Aggregation 8.4
File
src/EventSubscriber/ResponseSubscriber.php
View source
<?php
namespace Drupal\advagg\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Render\HtmlResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ResponseSubscriber implements EventSubscriberInterface {
protected $config;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->config = $config_factory
->get('advagg.settings');
}
public static function getSubscribedEvents() {
return [
KernelEvents::RESPONSE => [
[
'processResponse',
-9999,
],
[
'forceAbsolutePaths',
0,
],
],
];
}
public function processResponse(FilterResponseEvent $event) {
if ($this->config
->get('dns_prefetch')) {
$response = $event
->getResponse();
if (stripos($response->headers
->get('Content-Type'), 'text/html') === FALSE) {
return;
}
global $_advagg_prefetch;
if (empty($_advagg_prefetch)) {
return;
}
$_advagg_prefetch = array_unique($_advagg_prefetch);
$domains = '<head>';
foreach ($_advagg_prefetch as $domain) {
$domains .= "<link rel='dns-prefetch' href='{$domain}'>";
}
$response
->setContent(str_replace('<head>', $domains, $response
->getContent()));
}
}
public function forceAbsolutePaths(FilterResponseEvent $response) {
if (!$this->config
->get('path.convert.absolute')) {
return;
}
$response = $response
->getResponse();
if (!$response instanceof HtmlResponse) {
return;
}
$content = $response
->getContent();
$pattern = '/(<script src="|url\\("|rel="stylesheet" href=")(\\/[a-zA-Z0-0].*")/';
$response
->setContent(preg_replace_callback($pattern, [
$this,
'forceAbsolutePathsCallback',
], $content));
}
public function forceAbsolutePathsCallback(array $matches) {
global $base_root;
return "{$matches[1]}{$base_root}{$matches[2]}";
}
}