I have a problem with event subscriber. Here is the error:
The website encountered an unexpected error. Please try again later. Error: Call to a member function getRouteName() on null in Drupal\hello_world\EventSubscriber\HelloWorldRedirectSubscriber->onRequest() (line 58 of modules\custom\src\EventSubscriber\HelloWorldRedirectSubscriber.php).
and my code is:
<?php
namespace Drupal\hello_world\EventSubscriber;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
//use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\Routing\currentRouteMatch;
use Drupal\Core\Routing\LocalRedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\Core\Url;
/**
* Subscribers to the Kernel Request event and redirects to the
* homepage when the user has the "non_grata" role.
*/
class HelloWorldRedirectSubscriber implements EventSubscriberInterface {
/**
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser; // Store the current user as a class property
/**
* HelloWorldRedirectSubscriber constructor.
*
* @param \Drupal\Core\Session\AccountProxyInterface $currentUser
*/
public function __construct(AccountProxyInterface $currentUser) {
$this->currentUser = $currentUser;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
// $events['kernel.request'][] = ['onRequest', 0];
// più elegante:
$events[KernelEvents::REQUEST][] = ['onRequest', 0];
return $events;
}
/**
* Handler for the kernel request event.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
*/
public function onRequest(GetResponseEvent $event) {
//$request = $event->getRequest();
//$path = $request->getPathInfo();
// if ($path !== '/hello')
// {
// return;
// } BEST PRACTICE FOR KEEP DYNAMICITY: currentRouteMatch Service
$route_name = $this->currentRouteMatch->getRouteName();
// check against the route name (and not path name)
if ($route_name !== 'hello_world.hello')
{
return;
}
$roles = $this->currentUser->getRoles();
if (in_array('inaccettabile', $roles)) {
// $event->setResponse(new RedirectResponse('/'));
$url = Url::fromUri('internal:/');
// LocalRedirectResponse class redirect the user to a local (safe) path
$event->setResponse(new LocalRedirectResponse($url->toString()));
}
}
}
I cannot figure out what could be the problem. :\