Submitted by
Dmitro
on
Create file custom_base/src/EventSubscriber/FrontpageRedirectSubscriber.php:
<?php
namespace Drupal\custom_base\EventSubscriber;
use Drupal\Core\Path\PathMatcherInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Event subscriber to perform redirects based on user role.
*/
class FrontpageRedirectSubscriber implements EventSubscriberInterface {
/**
* Current logged in user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The path matcher.
*
* @var \Drupal\Core\Path\PathMatcherInterface
*/
protected $pathMatcher;
/**
* Constructs a new ViewsRedirectSubscriber object.
*
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\Path\PathMatcherInterface $path_matcher
* The path matcher service.
*/
public function __construct(
AccountInterface $current_user,
PathMatcherInterface $path_matcher
) {
$this->currentUser = $current_user;
$this->pathMatcher = $path_matcher;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = ['performRoleRedirect'];
return $events;
}
/**
* Performs redirect based on user role.
*/
public function performRoleRedirect(RequestEvent $event) {
$roles = $this->currentUser->getRoles();
$isFrontPage = $this->pathMatcher->isFrontPage();
if ($isFrontPage) {
foreach ($roles as $role) {
$url = NULL;
switch ($role) {
case ROLE_ADMIN:
$url = Url::fromRoute('view.admin.page')
->toString();
break;
case ROLE_READER:
$url = Url::fromRoute('view.reader_list.page_1')
->toString();
break;
case ROLE_MANAGER:
$url = Url::fromRoute('view.manager.page_1')
->toString();
break;
}
if (!empty($url)) {
$response = new RedirectResponse($url);
$event->setResponse($response);
$event->stopPropagation();
}
}
}
}
}
Add to servises.yml:
custom_base_frontpage.event_subscriber:
class: Drupal\custom_base\EventSubscriber\FrontpageRedirectSubscriber
arguments:
- '@current_user'
- '@path.matcher'
tags:
- { name: event_subscriber }