Fast404ExceptionHtmlSubscriber.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Config\ConfigFactoryInterface;
  4. use Drupal\Component\Utility\Html;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  7. use Symfony\Component\HttpKernel\HttpKernelInterface;
  8. /**
  9. * High-performance 404 exception subscriber.
  10. *
  11. * This subscriber will return a minimalist 404 response for HTML requests
  12. * without running a full page theming operation.
  13. */
  14. class Fast404ExceptionHtmlSubscriber extends HttpExceptionSubscriberBase {
  15. /**
  16. * The HTTP kernel.
  17. *
  18. * @var \Symfony\Component\HttpKernel\HttpKernelInterface
  19. */
  20. protected $httpKernel;
  21. /**
  22. * The config factory.
  23. *
  24. * @var \Drupal\Core\Config\ConfigFactoryInterface
  25. */
  26. protected $configFactory;
  27. /**
  28. * Constructs a new Fast404ExceptionHtmlSubscriber.
  29. *
  30. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
  31. * The configuration factory.
  32. * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
  33. * The HTTP Kernel service.
  34. */
  35. public function __construct(ConfigFactoryInterface $config_factory, HttpKernelInterface $http_kernel) {
  36. $this->configFactory = $config_factory;
  37. $this->httpKernel = $http_kernel;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. protected static function getPriority() {
  43. // A very high priority so that it can take precedent over anything else,
  44. // and thus be fast.
  45. return 200;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. protected function getHandledFormats() {
  51. return ['html'];
  52. }
  53. /**
  54. * Handles a 404 error for HTML.
  55. *
  56. * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
  57. * The event to process.
  58. */
  59. public function on404(GetResponseForExceptionEvent $event) {
  60. $request = $event->getRequest();
  61. $config = $this->configFactory->get('system.performance');
  62. $exclude_paths = $config->get('fast_404.exclude_paths');
  63. if ($config->get('fast_404.enabled') && $exclude_paths && !preg_match($exclude_paths, $request->getPathInfo())) {
  64. $fast_paths = $config->get('fast_404.paths');
  65. if ($fast_paths && preg_match($fast_paths, $request->getPathInfo())) {
  66. $fast_404_html = strtr($config->get('fast_404.html'), ['@path' => Html::escape($request->getUri())]);
  67. $response = new Response($fast_404_html, Response::HTTP_NOT_FOUND);
  68. $event->setResponse($response);
  69. }
  70. }
  71. }
  72. }