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;
50 protected static function getPriority() {
51 // A very high priority so that it can take precedent over anything else,
59 protected function getHandledFormats() {
64 * Handles a 404 error for HTML.
66 * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
67 * The event to process.
69 public function on404(GetResponseForExceptionEvent $event) {
70 $request = $event->getRequest();
72 $config = $this->configFactory->get('system.performance');
73 $exclude_paths = $config->get('fast_404.exclude_paths');
74 if ($config->get('fast_404.enabled') && $exclude_paths && !preg_match($exclude_paths, $request->getPathInfo())) {
75 $fast_paths = $config->get('fast_404.paths');
76 if ($fast_paths && preg_match($fast_paths, $request->getPathInfo())) {
77 $fast_404_html = strtr($config->get('fast_404.html'), ['@path' => Html::escape($request->getUri())]);
78 $response = new Response($fast_404_html, Response::HTTP_NOT_FOUND);
79 $event->setResponse($response);