/** * @param Request $request */ public function match(Request $request) { // Initialize the context that is also used by the generator (assuming matcher and generator share the same // context instance). $this->context->fromRequest($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" (parameters: %s)', $parameters['_route'], $this->parametersToString($parameters))); } $request->attributes->add($parameters); unset($parameters['_route']); unset($parameters['_controller']); $request->attributes->set('_route_params', $parameters); } catch (ResourceNotFoundException $e) { $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo()); 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(), strtoupper(implode(', ', $e->getAllowedMethods()))); throw new MethodNotAllowedException($e->getAllowedMethods(), $message); } }
/** * {@inheritdoc} */ public function getContext() { if (!isset($this->context)) { $this->context = new RequestContext(); $this->context->fromRequest($this->request); } return $this->context; }
/** * @return RequestContext */ public function getContext() { if (!$this->context) { $this->context = new RequestContext(); $this->context->fromRequest(\Request::getInstance()); } return $this->context; }
/** * Gets the request context. * * @return RequestContext The context * * @api */ public function getContext() { if (!isset($this->context)) { $this->context = new RequestContext(); $this->context->fromRequest($this->container->get('request_stack')->getCurrentRequest()); } return $this->context; }
/** * Gets the request context. * * @return RequestContext The context */ public function getContext() { if (!isset($this->context)) { $request = $this->container->get('request'); $this->context = new RequestContext(); $this->context->fromRequest($request); } return $this->context; }
/** * Gets the request context. * * @return RequestContext The context * * @api */ public function getContext() { if (!isset($this->context)) { /** @var Request $request */ $request = $this->getMasterRequest(); $this->context = new RequestContext(); $this->context->fromRequest($request); } return $this->context; }
/** * @dataProvider resolveProvider */ public function testResolve($path, $filter, $requestUrl, $expected) { if ($requestUrl) { $this->requestContext->fromRequest(Request::create($requestUrl)); } $storageDir = '/var/doctorwho/storage/images'; $this->ioService->expects($this->once())->method('loadBinaryFile')->with($path)->will($this->returnValue(new BinaryFile(array('uri' => "{$storageDir}/{$path}")))); $result = $this->imageResolver->resolve($path, $filter); $this->assertSame($expected, $result); }
private function __construct($routes) { $this->routeCollection = $routes; $this->request = Request::createFromGlobals(); $this->requestContext = new RequestContext(); $this->matcher = new UrlMatcher($routes, $this->requestContext->fromRequest($this->getRequest())); $this->dispatcher = new Dispatcher(); $this->dispatcher->addSubscriber(new RouterListener($this->matcher, new RequestStack())); $this->dispatcher->addSubscriber(new KernelExceptionListener()); $this->dispatcher->addSubscriber(new ResponseListener('UTF-8')); }
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { try { $this->request = $request; $pathInfo = $request->getPathInfo(); $this->loadRoutes($pathInfo); $this->loadGeneralConfig(); $this->loadZyncroAppConfig($pathInfo); $this->loadDatabaseConfig($pathInfo); $this->loadSecurityConfig($pathInfo); $this->loadTwig($pathInfo); $this->loadUtils(); $this->method = $request->getMethod(); $this->dispatcher->dispatch('request', new RequestEvent($request, $this->session, $this->securityConfig, $this->routes)); $this->loadApi(); $context = new Routing\RequestContext(); $matcher = new Routing\Matcher\UrlMatcher($this->routes, $context); $context->fromRequest($request); $request->attributes->add($matcher->match($request->getPathInfo())); $resolver = new ControllerResolver(); $controller = $resolver->getController($request); $arguments = $resolver->getArguments($request, $controller); $arguments[0] = $this; $response = call_user_func_array($controller, $arguments); } catch (Routing\Exception\ResourceNotFoundException $e) { $response = new Response('Not Found', 404); } catch (\Exception $e) { $response = new Response('An error occurred: ' . $e->getMessage(), 500); } return $response; }
public static function listener(RequestEvent $requestEvent) { $request = $requestEvent->getRequest(); $pathInfo = $request->getPathInfo(); $session = $requestEvent->getSession(); $configSecurity = $requestEvent->getSecurityConfig(); $routes = $requestEvent->getRoutes(); $context = new RequestContext(); $matcher = new UrlMatcher($routes, $context); $context->fromRequest($request); $matching = $matcher->match($pathInfo); $matchedRoute = $matching['_route']; if (isset($configSecurity['protected'])) { $protected = $configSecurity['protected']; $protectedRoutes = $protected['routes']; $sessionKey = $protected['session']; $notLoggedRoute = $protected['not_logged']; $loggedRoute = $protected['logged']; $redirectRoute = null; if ($session->get($sessionKey) && $matchedRoute === $notLoggedRoute) { $redirectRoute = $routes->get($loggedRoute); } if (!$session->get($sessionKey) && in_array($matchedRoute, $protectedRoutes)) { $redirectRoute = $routes->get($notLoggedRoute); } if ($redirectRoute) { $redirectResponse = new RedirectResponse($request->getBaseUrl() . $redirectRoute->getPath()); $redirectResponse->send(); } } }
private function getMatcherFromRequest($request) { $context = new Routing\RequestContext(); $context->fromRequest($request); $matcher = new Routing\Matcher\UrlMatcher($this->routes, $context); return $matcher; }
public function register(Container $container) { $container['request'] = function ($c) { return Request::createFromGlobals(); }; $container['requestStack'] = function ($c) { $stack = new RequestStack(); $stack->push($c['request']); return $stack; }; $container['requestContext'] = function ($c) { $rc = new RequestContext(); $rc->fromRequest($c['request']); return $rc; }; $container['resolver'] = function ($c) { return new ControllerResolver(); }; $container['httpKernel'] = function ($c) { return new HttpKernel($c['dispatcher'], $c['resolver'], $c['requestStack']); }; $container['router'] = function ($c) { $router = new ChainRouter($c['logger']); $router->add($c['staticRouter']); $router->add($c['nodeRouter']); return $router; }; $container['staticRouter'] = function ($c) { return new StaticRouter($c['routeCollection'], ['cache_dir' => (bool) $c['config']['devMode'] ? null : ROADIZ_ROOT . '/cache/routing', 'debug' => (bool) $c['config']['devMode'], 'generator_cache_class' => 'StaticUrlGenerator', 'matcher_cache_class' => 'StaticUrlMatcher'], $c['requestContext'], $c['logger']); }; $container['nodeRouter'] = function ($c) { return new NodeRouter($c['em'], ['cache_dir' => (bool) $c['config']['devMode'] ? null : ROADIZ_ROOT . '/cache/routing', 'debug' => (bool) $c['config']['devMode'], 'generator_cache_class' => 'NodeUrlGenerator', 'matcher_cache_class' => 'NodeUrlMatcher'], $c['requestContext'], $c['logger'], $c['stopwatch']); }; $container['urlGenerator'] = function ($c) { return $c['staticRouter']->getGenerator(); }; $container['httpUtils'] = function ($c) { return new HttpUtils($c['router'], $c['router']); }; $container['routeListener'] = function ($c) { return new TimedRouteListener($c['router'], $c['requestContext'], null, $c['requestStack'], $c['stopwatch']); }; $container['routeCollection'] = function ($c) { if (isset($c['config']['install']) && true === $c['config']['install']) { /* * Get Install routes */ $installClassname = Kernel::INSTALL_CLASSNAME; $installClassname::setupDependencyInjection($c); return new InstallRouteCollection($installClassname); } else { /* * Get App routes */ $rCollection = new RoadizRouteCollection($c['backendClass'], $c['frontendThemes'], SettingsBag::get('static_domain_name'), $c['stopwatch']); return $rCollection; } }; return $container; }
public function route($url) { try { $context = new RequestContext(); $context->fromRequest($this->_request); $closure = function () { return $this->_container->get('routes'); }; $arrpar = array(); if (!DEVELOPMENT_ENVIRONMENT) { $arrpar['cache_dir'] = ROUTECACHE; } else { \Debug::addRoutes($closure); } $router = new SymfonyRouter(new ClosureLoader(), $closure, $arrpar, $context); $parameters = $router->match($url); $this->_controller = $parameters["controller"]; $this->_method = $parameters["action"]; $this->_route = $parameters["_route"]; unset($parameters["controller"]); unset($parameters["action"]); unset($parameters["_route"]); $this->_args = $parameters; } catch (ResourceNotFoundException $e) { $this->_route = ""; } catch (\Symfony\Component\Routing\Exception\MethodNotAllowedException $ema) { $this->_route = ""; throw new \GL\Core\Exception\MethodNotAllowedException(); } return $this->_route != ""; }
/** * @return array|bool */ protected function resolveController() { try { // doctrine mabo jambo to prepare route detection $context = new RequestContext(); $context->fromRequest($this->request); $matcher = new UrlMatcher($this->routeCollection, $context); // try detecting controller & stuff $this->request->attributes->add($matcher->match($this->request->getPathInfo())); // resolve controller $resolver = new ControllerResolver(); $controller = $resolver->getController($this->request); $controller = $this->assembleController($controller); // adding request and response variables to the controller if (!empty($controller[0]) && $controller[0] instanceof AbstractSimplexController) { $controller[0]->setRequest($this->request)->setResponse($this->response); } else { // or as attributes for a 'function' controller $req = array('request' => $this->request, 'response' => $this->response); $this->request->attributes->add($req); } // parsing arguments for the request and adding a last argument the request parameter itself $arguments = $resolver->getArguments($this->request, $controller); return array($controller, $arguments); } catch (ResourceNotFoundException $e) { } return false; }
/** * @param Request $request * * @return Response */ public function getControllerResponse(Request $request) { // build the context from the Request that was passed $this->context->fromRequest($request); // instantiate the router with the correct settings so it can automatically perform caching $router = new Router($this->loader, Configuration::instance()->setting('base', 'routeFile', 'routes.php'), ['cache_dir' => Configuration::instance()->setting('base', 'routeCacheDir')], $this->context); // TODO make this configurable // default controller $match = ["_controller" => '\\Controllers\\HomeController', "_action" => "index"]; try { $match = $router->matchRequest($request); } catch (\Exception $ex) { if ($ex instanceof ResourceNotFoundException) { // TODO improve this return new Response("404 Not Found", 404); } elseif ($ex instanceof MethodNotAllowedException) { // TODO improve this return new Response("Current request method is not allowed for this route", 401); } } // dynamically instantiate a new controller and pass it the Request object $controller = new $match['_controller']($request); $action = $match['_action']; // parse out all parameters (those keys that do not start with an underscore) $parameters = $this->getParameters($match); // we pass $match as last parameter because it also contains all key-value pairs for the arguments of the action $responseText = call_user_func_array([$controller, $action], $parameters); // wrap the response that was generated by the controller $response = new Response($responseText); return $response; }
/** * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) { return; } // @todo make endpoint(s) customizable if ($event->getRequest()->getMethod() !== 'POST') { return; } if ($event->getRequest()->getPathInfo() != '/xmlrpc' && $event->getRequest()->getPathInfo() != '/xmlrpc.php') { return; } try { $request = $this->requestGenerator->generateFromRequest($event->getRequest()); if (isset($this->logger)) { $this->logger->debug((string) $request); } } catch (UnexpectedValueException $e) { $event->setResponse(new Response("Invalid request XML\n" . $e->getMessage(), 400)); return; } // @todo refactor to dynamically set follow-up events instead of testing (cors bundle like) $request->attributes->set('IsXmlRpcRequest', true); $requestContext = new RequestContext(); $requestContext->fromRequest($request); $originalContext = $this->router->getContext(); $this->router->setContext($requestContext); $response = $this->httpKernel->handle($request); $event->setResponse($response); $this->router->setContext($originalContext); if ($response instanceof Response) { $event->setResponse($response); } }
public function match(Request $request) { $context = new RequestContext(); $context->fromRequest($request); $this->context = $context; $matcher = new UrlMatcher($this->getRouteCollection(), $context); return $matcher->match($request->getPathInfo()); }
/** * {@inheritdoc} */ public function finalMatch(RouteCollection $collection, Request $request) { $this->routes = $collection; $context = new RequestContext(); $context->fromRequest($request); $this->setContext($context); return $this->match($request->getPathInfo()); }
/** * @param Request $request * @param string $path */ public function __construct(Request $request, $path = '') { $context = new RequestContext(); $context->fromRequest($request); $this->request = $request; $this->requestContext = $context; $this->path = $path; }
public function fromRequest(Request $request) { parent::fromRequest($request); // Inject the query string as a parameter for Symfony versions <= 2.2 if (!method_exists($this, 'getQueryString') && '' !== ($qs = $request->server->get('QUERY_STRING'))) { $this->setParameter('QUERY_STRING', $qs); } }
protected function init(RouteCollection $routes) { $context = new RequestContext(); $context->fromRequest($this->request); $context->setBaseUrl($this->options['basepath']); $this->matcher = new UrlMatcher($routes, $context); $this->generator = new UrlGenerator($routes, $context); }
/** * Get an object instance of UrlGenerator class. * * @return UrlGenerator */ public static function getInstance() { $configDirectory = new YamlFileLoader(new FileLocator(array(__DIR__ . '/../../Resources/config'))); $captchaRoutes = $configDirectory->load('routing.yml'); $requestContext = new RequestContext(); $requestContext->fromRequest(Request::createFromGlobals()); return new SymfonyUrlGenerator($captchaRoutes, $requestContext); }
/** * @param Request $request * @return array */ public function match(Request $request) : array { $context = new RequestContext(); $context->fromRequest($request); include_once ROOT . 'cache/router_matcher.php'; $matcher = new ProjectUrlMatcher($context); return $matcher->matchRequest($request); }
public function testSimpleRoute() { $context = new RequestContext(); $request = Request::create("/hello"); $context->fromRequest($request); $matcher = new UrlMatcher($this->routes, $context); $parameters = $matcher->match('/hello'); $this->assertJsonStringEqualsJsonString('{"_route": "hello", "_controller": "foo"}', json_encode($parameters)); }
/** * {@inheritdoc} */ public function fromRequest(Request $request) { parent::fromRequest($request); $this->setBasePath($path = $request->getBasePath()); $this->setBaseUrl($request->server->get('HTTP_MOD_REWRITE') == 'On' ? $path : "{$path}/index.php"); $this->setScriptPath($request->server->get('SCRIPT_FILENAME')); $this->setReferer($request->headers->get('referer')); $this->setSchemeAndHttpHost($request->getSchemeAndHttpHost()); }
/** * {@inheritdoc} */ public function fromRequest(Request $request) { parent::fromRequest($request); // @todo Extract the code in DrupalKernel::initializeRequestGlobals. // See https://www.drupal.org/node/2404601 if (isset($GLOBALS['base_url'])) { $this->setCompleteBaseUrl($GLOBALS['base_url']); } }
/** * This listener is run when the KernelEvents::REQUEST event is triggered * * This is responsible for setting up the routing information * * @param GetResponseEvent $event * @throws \BadMethodCallException * @return null */ public function on_kernel_request(GetResponseEvent $event) { $request = $event->getRequest(); $context = new RequestContext(); $context->fromRequest($request); $matcher = src_get_url_matcher($this->manager, $context, $this->root_path, $this->php_ext); $router_listener = new RouterListener($matcher, $context); $router_listener->onKernelRequest($event); }
/** * {@inheritdoc} */ public function __invoke(Request $request) { $context = new RequestContext(); $context->fromRequest($request); $this->eventDispatcher->addSubscriber(new RouterListener(new UrlMatcher($this->routeCollection, $context))); $kernel = new HttpKernel($this->eventDispatcher, new ControllerResolverActionResolverAdapter($this->actionResolver)); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response); }
/** * @return RouteParametersItem */ public function work() { RouteCache::work(self::$routesFile); $this->addRoutesToRouteCollection(); $context = new RequestContext(); $context->fromRequest(Request::request()); $matcher = new UrlMatcher($this->routeCollection, $context); $parameters = $matcher->matchRequest(Request::request()); return new RouteParametersItem($parameters); }
/** * @dataProvider resolveProvider */ public function testResolve($path, $filter, $variationPath, $requestUrl, $expected) { if ($requestUrl) { $this->requestContext->fromRequest(Request::create($requestUrl)); } $this->ioService->expects($this->any())->method('loadBinaryFile')->will($this->returnValue(new BinaryFile(array('uri' => $variationPath)))); $this->variationPathGenerator->expects($this->any())->method('getVariationPath')->willReturn($variationPath); $result = $this->imageResolver->resolve($path, $filter); $this->assertSame($expected, $result); }