3 namespace Drupal\Core\EventSubscriber;
5 use Drupal\Core\Config\ConfigFactoryInterface;
6 use Drupal\Component\Utility\Html;
7 use Symfony\Component\HttpFoundation\Response;
8 use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
9 use Symfony\Component\HttpKernel\HttpKernelInterface;
12 * High-performance 404 exception subscriber.
14 * This subscriber will return a minimalist 404 response for HTML requests
15 * without running a full page theming operation.
17 class Fast404ExceptionHtmlSubscriber extends HttpExceptionSubscriberBase {
22 * @var \Symfony\Component\HttpKernel\HttpKernelInterface
24 protected $httpKernel;
29 * @var \Drupal\Core\Config\ConfigFactoryInterface
31 protected $configFactory;
34 * Constructs a new Fast404ExceptionHtmlSubscriber.
36 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
37 * The configuration factory.
38 * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
39 * The HTTP Kernel service.
41 public function __construct(ConfigFactoryInterface $config_factory, HttpKernelInterface $http_kernel) {
42 $this->configFactory = $config_factory;
43 $this->httpKernel = $http_kernel;
49 protected static function getPriority() {
50 // A very high priority so that it can take precedent over anything else,
58 protected function getHandledFormats() {
63 * Handles a 404 error for HTML.
65 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
66 * The event to process.
68 public function on404(GetResponseForExceptionEvent $event) {
69 $request = $event->getRequest();
71 $config = $this->configFactory->get('system.performance');
72 $exclude_paths = $config->get('fast_404.exclude_paths');
73 if ($config->get('fast_404.enabled') && $exclude_paths && !preg_match($exclude_paths, $request->getPathInfo())) {
74 $fast_paths = $config->get('fast_404.paths');
75 if ($fast_paths && preg_match($fast_paths, $request->getPathInfo())) {
76 $fast_404_html = strtr($config->get('fast_404.html'), ['@path' => Html::escape($request->getUri())]);
77 $response = new Response($fast_404_html, Response::HTTP_NOT_FOUND);
78 $event->setResponse($response);