vendor/symfony/http-kernel/EventListener/RouterListener.php line 111

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <[email protected]>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\EventListener;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\RequestStack;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  17. use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
  18. use Symfony\Component\HttpKernel\Event\RequestEvent;
  19. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  20. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  21. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  22. use Symfony\Component\HttpKernel\Kernel;
  23. use Symfony\Component\HttpKernel\KernelEvents;
  24. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  25. use Symfony\Component\Routing\Exception\NoConfigurationException;
  26. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  27. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  28. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  29. use Symfony\Component\Routing\RequestContext;
  30. use Symfony\Component\Routing\RequestContextAwareInterface;
  31. /**
  32. * Initializes the context from the request and sets request attributes based on a matching route.
  33. *
  34. * @author Fabien Potencier <[email protected]>
  35. * @author Yonel Ceruto <[email protected]>
  36. *
  37. * @final
  38. */
  39. class RouterListener implements EventSubscriberInterface
  40. {
  41. private $matcher;
  42. private $context;
  43. private $logger;
  44. private $requestStack;
  45. private $projectDir;
  46. private $debug;
  47. /**
  48. * @param UrlMatcherInterface|RequestMatcherInterface $matcher The Url or Request matcher
  49. * @param RequestContext|null $context The RequestContext (can be null when $matcher implements RequestContextAwareInterface)
  50. *
  51. * @throws \InvalidArgumentException
  52. */
  53. public function __construct($matcher, RequestStack $requestStack, ?RequestContext $context = null, ?LoggerInterface $logger = null, ?string $projectDir = null, bool $debug = true)
  54. {
  55. if (!$matcher instanceof UrlMatcherInterface && !$matcher instanceof RequestMatcherInterface) {
  56. throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
  57. }
  58. if (null === $context && !$matcher instanceof RequestContextAwareInterface) {
  59. throw new \InvalidArgumentException('You must either pass a RequestContext or the matcher must implement RequestContextAwareInterface.');
  60. }
  61. $this->matcher = $matcher;
  62. $this->context = $context ?? $matcher->getContext();
  63. $this->requestStack = $requestStack;
  64. $this->logger = $logger;
  65. $this->projectDir = $projectDir;
  66. $this->debug = $debug;
  67. }
  68. private function setCurrentRequest(?Request $request = null)
  69. {
  70. if (null !== $request) {
  71. try {
  72. $this->context->fromRequest($request);
  73. } catch (\UnexpectedValueException $e) {
  74. throw new BadRequestHttpException($e->getMessage(), $e, $e->getCode());
  75. }
  76. }
  77. }
  78. /**
  79. * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator
  80. * operates on the correct context again.
  81. */
  82. public function onKernelFinishRequest(FinishRequestEvent $event)
  83. {
  84. $this->setCurrentRequest($this->requestStack->getParentRequest());
  85. }
  86. public function onKernelRequest(RequestEvent $event)
  87. {
  88. $request = $event->getRequest();
  89. $this->setCurrentRequest($request);
  90. if ($request->attributes->has('_controller')) {
  91. // routing is already done
  92. return;
  93. }
  94. // add attributes based on the request (routing)
  95. try {
  96. // matching a request is more powerful than matching a URL path + context, so try that first
  97. if ($this->matcher instanceof RequestMatcherInterface) {
  98. $parameters = $this->matcher->matchRequest($request);
  99. } else {
  100. $parameters = $this->matcher->match($request->getPathInfo());
  101. }
  102. if (null !== $this->logger) {
  103. $this->logger->info('Matched route "{route}".', [
  104. 'route' => $parameters['_route'] ?? 'n/a',
  105. 'route_parameters' => $parameters,
  106. 'request_uri' => $request->getUri(),
  107. 'method' => $request->getMethod(),
  108. ]);
  109. }
  110. $request->attributes->add($parameters);
  111. unset($parameters['_route'], $parameters['_controller']);
  112. $request->attributes->set('_route_params', $parameters);
  113. } catch (ResourceNotFoundException $e) {
  114. $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getUriForPath($request->getPathInfo()));
  115. if ($referer = $request->headers->get('referer')) {
  116. $message .= sprintf(' (from "%s")', $referer);
  117. }
  118. throw new NotFoundHttpException($message, $e);
  119. } catch (MethodNotAllowedException $e) {
  120. $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getUriForPath($request->getPathInfo()), implode(', ', $e->getAllowedMethods()));
  121. throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
  122. }
  123. }
  124. public function onKernelException(ExceptionEvent $event)
  125. {
  126. if (!$this->debug || !($e = $event->getThrowable()) instanceof NotFoundHttpException) {
  127. return;
  128. }
  129. if ($e->getPrevious() instanceof NoConfigurationException) {
  130. $event->setResponse($this->createWelcomeResponse());
  131. }
  132. }
  133. public static function getSubscribedEvents(): array
  134. {
  135. return [
  136. KernelEvents::REQUEST => [['onKernelRequest', 32]],
  137. KernelEvents::FINISH_REQUEST => [['onKernelFinishRequest', 0]],
  138. KernelEvents::EXCEPTION => ['onKernelException', -64],
  139. ];
  140. }
  141. private function createWelcomeResponse(): Response
  142. {
  143. $version = Kernel::VERSION;
  144. $projectDir = realpath((string) $this->projectDir).\DIRECTORY_SEPARATOR;
  145. $docVersion = substr(Kernel::VERSION, 0, 3);
  146. ob_start();
  147. include \dirname(__DIR__).'/Resources/welcome.html.php';
  148. return new Response(ob_get_clean(), Response::HTTP_NOT_FOUND);
  149. }
  150. }