Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Drupalhello_worldEventSubscriber;
  4.  
  5. use DrupalCoreSessionAccountProxyInterface;
  6. use SymfonyComponentEventDispatcherEventSubscriberInterface;
  7. //use SymfonyComponentHttpFoundationRedirectResponse;
  8. use SymfonyComponentHttpKernelEventGetResponseEvent;
  9. use DrupalCoreRoutingcurrentRouteMatch;
  10. use DrupalCoreRoutingLocalRedirectResponse;
  11. use SymfonyComponentHttpKernelKernelEvents;
  12. use DrupalCoreUrl;
  13.  
  14.  
  15. /**
  16. * Subscribers to the Kernel Request event and redirects to the
  17. * homepage when the user has the "non_grata" role.
  18. */
  19. class HelloWorldRedirectSubscriber implements EventSubscriberInterface {
  20.  
  21. /**
  22. * @var DrupalCoreSessionAccountProxyInterface
  23. */
  24. protected $currentUser; // Store the current user as a class property
  25.  
  26. /**
  27. * HelloWorldRedirectSubscriber constructor.
  28. *
  29. * @param DrupalCoreSessionAccountProxyInterface $currentUser
  30. */
  31. public function __construct(AccountProxyInterface $currentUser) {
  32. $this->currentUser = $currentUser;
  33. }
  34.  
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public static function getSubscribedEvents() {
  39. // $events['kernel.request'][] = ['onRequest', 0];
  40. // più elegante:
  41. $events[KernelEvents::REQUEST][] = ['onRequest', 0];
  42. return $events;
  43. }
  44.  
  45. /**
  46. * Handler for the kernel request event.
  47. *
  48. * @param SymfonyComponentHttpKernelEventGetResponseEvent $event
  49. */
  50.  
  51. public function onRequest(GetResponseEvent $event) {
  52. //$request = $event->getRequest();
  53. //$path = $request->getPathInfo();
  54. // if ($path !== '/hello')
  55. // {
  56. // return;
  57. // } BEST PRACTICE FOR KEEP DYNAMICITY: currentRouteMatch Service
  58. $route_name = $this->currentRouteMatch->getRouteName();
  59.  
  60. // check against the route name (and not path name)
  61. if ($route_name !== 'hello_world.hello')
  62. {
  63. return;
  64. }
  65.  
  66. $roles = $this->currentUser->getRoles();
  67.  
  68. if (in_array('inaccettabile', $roles)) {
  69. // $event->setResponse(new RedirectResponse('/'));
  70. $url = Url::fromUri('internal:/');
  71. // LocalRedirectResponse class redirect the user to a local (safe) path
  72. $event->setResponse(new LocalRedirectResponse($url->toString()));
  73. }
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement