Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / lib / Drupal / Core / EventSubscriber / Fast404ExceptionHtmlSubscriber.php
1 <?php
2
3 namespace Drupal\Core\EventSubscriber;
4
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;
10
11 /**
12  * High-performance 404 exception subscriber.
13  *
14  * This subscriber will return a minimalist 404 response for HTML requests
15  * without running a full page theming operation.
16  */
17 class Fast404ExceptionHtmlSubscriber extends HttpExceptionSubscriberBase {
18
19   /**
20    * The HTTP kernel.
21    *
22    * @var \Symfony\Component\HttpKernel\HttpKernelInterface
23    */
24   protected $httpKernel;
25
26   /**
27    * The config factory.
28    *
29    * @var \Drupal\Core\Config\ConfigFactoryInterface
30    */
31   protected $configFactory;
32
33   /**
34    * Constructs a new Fast404ExceptionHtmlSubscriber.
35    *
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.
40    */
41   public function __construct(ConfigFactoryInterface $config_factory, HttpKernelInterface $http_kernel) {
42     $this->configFactory = $config_factory;
43     $this->httpKernel = $http_kernel;
44   }
45
46   /**
47    * {@inheritdoc}
48    */
49   protected static function getPriority() {
50     // A very high priority so that it can take precedent over anything else,
51     // and thus be fast.
52     return 200;
53   }
54
55   /**
56    * {@inheritdoc}
57    */
58   protected function getHandledFormats() {
59     return ['html'];
60   }
61
62   /**
63    * Handles a 404 error for HTML.
64    *
65    * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
66    *   The event to process.
67    */
68   public function on404(GetResponseForExceptionEvent $event) {
69     $request = $event->getRequest();
70
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);
79       }
80     }
81   }
82
83 }