AmpEventSubscriber.php in Accelerated Mobile Pages (AMP) 8.3
File
src/EventSubscriber/AmpEventSubscriber.php
View source
<?php
namespace Drupal\amp\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\amp\Routing\AmpContext;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
class AmpEventSubscriber extends ServiceProviderBase implements EventSubscriberInterface {
protected $ampContext;
protected $routeMatch;
public function __construct(AmpContext $ampContext, RouteMatchInterface $routeMatch) {
$this->ampContext = $ampContext;
$this->routeMatch = $routeMatch;
}
public function onView(GetResponseForControllerResultEvent $event) {
$wrapper_format = isset($_GET['_wrapper_format']) ? $_GET['_wrapper_format'] : '';
if (!empty($wrapper_format) && !in_array($wrapper_format, [
'html',
'amp',
])) {
return;
}
$amp_wrapper_format = isset($_GET['_wrapper_format']) && $_GET['_wrapper_format'] == 'amp';
$isAmpRoute = $this->ampContext
->isAmpRoute($this->routeMatch, NULL, FALSE);
$request = $event
->getRequest();
if (!$isAmpRoute) {
$request->query
->set(MainContentViewSubscriber::WRAPPER_FORMAT, 'html');
}
elseif (!$amp_wrapper_format && $isAmpRoute) {
$request->query
->set(MainContentViewSubscriber::WRAPPER_FORMAT, 'amp');
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::VIEW][] = [
'onView',
100,
];
return $events;
}
}