I need to redirect all existing links targeting a few hand-picked nodes to an external domain. I created an EventSubscriber listening to RequestEvents
my.services.yml
services:
my.request_subscriber:
class: Drupal\my\EventSubscriber\EventSubscriber
arguments: ['@current_route_match', '@redirect.checker']
tags:
- { name: event_subscriber }
EventSubscriber.php
/* trimmed constructor, etc. for simplicity */
public static function getSubscribedEvents() {
// This needs to run before Redirect module
$events[KernelEvents::REQUEST][] = ['onKernelRequestCheckRedirect', 34];
return $events;
}
public function onKernelRequestCheckRedirect(RequestEvent $event) {
// the follwing lines are taken from redirect module
// @see https://git.drupalcode.org/project/redirect/-/blob/8.x-1.x/src/EventSubscriber/RedirectRequestSubscriber.php#L111
$request = clone $event->getRequest();
if (!$this->checker->canRedirect($request)) {
return;
}
/**
* No matter which route I visit, the $this->routeMatch->getRouteObject is always null,
* therefore the following lines also don't work as I hoped
*/
$routeName = $this->routeMatch->getRouteName(); // returns NULL :(
$nodeId = $this->routeMatch->getParameter('node'); // returns NULL :(
if ($routeName !== 'entity.node.canonical' || !in_array($nodeId, [MY_HANDPICKED_NODE_IDS]) ) {
return;
}
else {
// do $event->setResponse(my TrustedRedirectResponse);
}
}
Why is my route object always NULL? How do I get the routing information in my subscriber?