CustomPageExceptionHtmlSubscriber.php in Drupal 8
File
core/lib/Drupal/Core/EventSubscriber/CustomPageExceptionHtmlSubscriber.php
View source
<?php
namespace Drupal\Core\EventSubscriber;
use Drupal\Core\Access\AccessManagerInterface;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\AccessAwareRouterInterface;
use Drupal\Core\Routing\RedirectDestinationInterface;
use Drupal\Core\Url;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
class CustomPageExceptionHtmlSubscriber extends DefaultExceptionHtmlSubscriber {
protected $configFactory;
protected $accessManager;
public function __construct(ConfigFactoryInterface $config_factory, HttpKernelInterface $http_kernel, LoggerInterface $logger, RedirectDestinationInterface $redirect_destination, UrlMatcherInterface $access_unaware_router, AccessManagerInterface $access_manager) {
parent::__construct($http_kernel, $logger, $redirect_destination, $access_unaware_router);
$this->configFactory = $config_factory;
$this->accessManager = $access_manager;
}
protected static function getPriority() {
return -50;
}
public function on403(GetResponseForExceptionEvent $event) {
$custom_403_path = $this->configFactory
->get('system.site')
->get('page.403');
if (!empty($custom_403_path)) {
$this
->makeSubrequestToCustomPath($event, $custom_403_path, Response::HTTP_FORBIDDEN);
}
}
public function on404(GetResponseForExceptionEvent $event) {
$custom_404_path = $this->configFactory
->get('system.site')
->get('page.404');
if (!empty($custom_404_path)) {
$this
->makeSubrequestToCustomPath($event, $custom_404_path, Response::HTTP_NOT_FOUND);
}
}
protected function makeSubrequestToCustomPath(GetResponseForExceptionEvent $event, $custom_path, $status_code) {
$url = Url::fromUserInput($custom_path);
if ($url
->isRouted()) {
$access_result = $this->accessManager
->checkNamedRoute($url
->getRouteName(), $url
->getRouteParameters(), NULL, TRUE);
$request = $event
->getRequest();
if (!$request->attributes
->has(AccessAwareRouterInterface::ACCESS_RESULT)) {
$request->attributes
->set(AccessAwareRouterInterface::ACCESS_RESULT, $access_result);
}
else {
$existing_access_result = $request->attributes
->get(AccessAwareRouterInterface::ACCESS_RESULT);
if ($existing_access_result instanceof RefinableCacheableDependencyInterface) {
$existing_access_result
->addCacheableDependency($access_result);
}
}
if (!$access_result
->isAllowed()) {
return;
}
}
$this
->makeSubrequest($event, $custom_path, $status_code);
}
}