You are here

public function RouterListener::onKernelRequest in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 vendor/symfony/http-kernel/EventListener/RouterListener.php \Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest()

File

vendor/symfony/http-kernel/EventListener/RouterListener.php, line 116

Class

RouterListener
Initializes the context from the request and sets request attributes based on a matching route.

Namespace

Symfony\Component\HttpKernel\EventListener

Code

public function onKernelRequest(GetResponseEvent $event) {
  $request = $event
    ->getRequest();

  // initialize the context that is also used by the generator (assuming matcher and generator share the same context instance)
  // we call setCurrentRequest even if most of the time, it has already been done to keep compatibility
  // with frameworks which do not use the Symfony service container
  // when we have a RequestStack, no need to do it
  if (null !== $this->requestStack) {
    $this
      ->setCurrentRequest($request);
  }
  if ($request->attributes
    ->has('_controller')) {

    // routing is already done
    return;
  }

  // add attributes based on the request (routing)
  try {

    // matching a request is more powerful than matching a URL path + context, so try that first
    if ($this->matcher instanceof RequestMatcherInterface) {
      $parameters = $this->matcher
        ->matchRequest($request);
    }
    else {
      $parameters = $this->matcher
        ->match($request
        ->getPathInfo());
    }
    if (null !== $this->logger) {
      $this->logger
        ->info(sprintf('Matched route "%s".', isset($parameters['_route']) ? $parameters['_route'] : 'n/a'), array(
        'route_parameters' => $parameters,
        'request_uri' => $request
          ->getUri(),
      ));
    }
    $request->attributes
      ->add($parameters);
    unset($parameters['_route'], $parameters['_controller']);
    $request->attributes
      ->set('_route_params', $parameters);
  } catch (ResourceNotFoundException $e) {
    $message = sprintf('No route found for "%s %s"', $request
      ->getMethod(), $request
      ->getPathInfo());
    if ($referer = $request->headers
      ->get('referer')) {
      $message .= sprintf(' (from "%s")', $referer);
    }
    throw new NotFoundHttpException($message, $e);
  } catch (MethodNotAllowedException $e) {
    $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request
      ->getMethod(), $request
      ->getPathInfo(), implode(', ', $e
      ->getAllowedMethods()));
    throw new MethodNotAllowedHttpException($e
      ->getAllowedMethods(), $message, $e);
  }
}