Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Drupalhello_worldEventSubscriber;
- use DrupalCoreSessionAccountProxyInterface;
- use SymfonyComponentEventDispatcherEventSubscriberInterface;
- //use SymfonyComponentHttpFoundationRedirectResponse;
- use SymfonyComponentHttpKernelEventGetResponseEvent;
- use DrupalCoreRoutingcurrentRouteMatch;
- use DrupalCoreRoutingLocalRedirectResponse;
- use SymfonyComponentHttpKernelKernelEvents;
- use DrupalCoreUrl;
- /**
- * Subscribers to the Kernel Request event and redirects to the
- * homepage when the user has the "non_grata" role.
- */
- class HelloWorldRedirectSubscriber implements EventSubscriberInterface {
- /**
- * @var DrupalCoreSessionAccountProxyInterface
- */
- protected $currentUser; // Store the current user as a class property
- /**
- * HelloWorldRedirectSubscriber constructor.
- *
- * @param DrupalCoreSessionAccountProxyInterface $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 SymfonyComponentHttpKernelEventGetResponseEvent $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()));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement