AccessDeniedSubscriber.php in Drupal 8
File
core/modules/user/src/EventSubscriber/AccessDeniedSubscriber.php
View source
<?php
namespace Drupal\user\EventSubscriber;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class AccessDeniedSubscriber implements EventSubscriberInterface {
protected $account;
public function __construct(AccountInterface $account) {
$this->account = $account;
}
public function onException(GetResponseForExceptionEvent $event) {
$exception = $event
->getException();
if ($exception instanceof AccessDeniedHttpException) {
$route_name = RouteMatch::createFromRequest($event
->getRequest())
->getRouteName();
$redirect_url = NULL;
if ($this->account
->isAuthenticated()) {
switch ($route_name) {
case 'user.login':
$redirect_url = Url::fromRoute('entity.user.canonical', [
'user' => $this->account
->id(),
], [
'absolute' => TRUE,
]);
break;
case 'user.register':
$redirect_url = Url::fromRoute('entity.user.edit_form', [
'user' => $this->account
->id(),
], [
'absolute' => TRUE,
]);
break;
}
}
elseif ($route_name === 'user.page') {
$redirect_url = Url::fromRoute('user.login', [], [
'absolute' => TRUE,
]);
}
if ($redirect_url) {
$event
->setResponse(new RedirectResponse($redirect_url
->toString()));
}
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::EXCEPTION][] = [
'onException',
75,
];
return $events;
}
}