[ Index ]

PHP Cross Reference of phpBB-3.3.3-deutsch

title

Body

[close]

/vendor/symfony/http-kernel/EventListener/ -> RouterListener.php (source)

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


Generated: Sun Feb 14 20:08:31 2021 Cross-referenced by PHPXref 0.7.1