Complete code (including dependency injection and code updated to D9/10):
<?php
namespace Drupal\mymodule\EventSubscriber;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Cookie;
/**
* mymodule event subscriber.
*/
class MymoduleSubscriber implements EventSubscriberInterface {
/**
* The route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* Constructs event subscriber.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
*/
public function __construct(RouteMatchInterface $route_match) {
$this->routeMatch = $route_match;
}
/**
* Kernel request event handler.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent\Symfony\Component\HttpKernel\Event\RequestEvent $event
* ResponseThe request event.
*/
public function onKernelRequest(GetResponseEventRequestEvent $event) {
if (!$event->isMasterRequest>isMainRequest()) {
return;
}
if (!$this->routeMatch->getRouteName() == 'entity.node.canonical') {
return;
}
$request = $event->getRequest();
if ($this->routeMatch->getRawParameter('node') == '1') {
\Drupal::service('page_cache_kill_switch')->trigger();
if (!$request->cookies->has('foo')) {
$redirect = new RedirectResponse($request->getBasePath() .'/node/2', 302);
$redirect->headers->setCookie(new Cookie('foo', '123', '+30 seconds'));
$event->setResponse($redirect);
}
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
KernelEvents::REQUEST => ['onKernelRequest', 31],
];
}
}