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 action(RouterInterface $router, RequestContext $context) { $request = Request::createFromGlobals(); $bPath = $context->getPathInfo(); try { $parameters = $router->match($bPath); var_dump($parameters); $_controller = $parameters["_controller"]; $_controller = explode(":", $_controller); $class = $_controller[0]; $action = strtolower($_controller[1]) . "Action"; $class = new $class(); ob_start(); if (method_exists($class, $action)) { $class->{$action}($request, new JsonResponse()); $response = new Response(ob_get_clean()); } else { $response = new Response('Not Found', 404); } } catch (ResourceNotFoundException $e) { $response = new Response('Not Found', 404); } catch (Exception $e) { $response = new Response('An error occurred', 500); } $response->send(); }
public function test() { $coll = new RouteCollection(); $coll->add('foo', new Route('/foo', array(), array('_method' => 'POST'))); $coll->add('bar', new Route('/bar/{id}', array(), array('id' => '\\d+'))); $coll->add('bar1', new Route('/bar/{name}', array(), array('id' => '\\w+', '_method' => 'POST'))); $coll->add('bar2', new Route('/foo', array(), array(), array(), 'baz')); $coll->add('bar3', new Route('/foo1', array(), array(), array(), 'baz')); $coll->add('bar4', new Route('/foo2', array(), array(), array(), 'baz', array(), array(), 'context.getMethod() == "GET"')); $context = new RequestContext(); $context->setHost('baz'); $matcher = new TraceableUrlMatcher($coll, $context); $traces = $matcher->getTraces('/babar'); $this->assertEquals(array(0, 0, 0, 0, 0, 0), $this->getLevels($traces)); $traces = $matcher->getTraces('/foo'); $this->assertEquals(array(1, 0, 0, 2), $this->getLevels($traces)); $traces = $matcher->getTraces('/bar/12'); $this->assertEquals(array(0, 2), $this->getLevels($traces)); $traces = $matcher->getTraces('/bar/dd'); $this->assertEquals(array(0, 1, 1, 0, 0, 0), $this->getLevels($traces)); $traces = $matcher->getTraces('/foo1'); $this->assertEquals(array(0, 0, 0, 0, 2), $this->getLevels($traces)); $context->setMethod('POST'); $traces = $matcher->getTraces('/foo'); $this->assertEquals(array(2), $this->getLevels($traces)); $traces = $matcher->getTraces('/bar/dd'); $this->assertEquals(array(0, 1, 2), $this->getLevels($traces)); $traces = $matcher->getTraces('/foo2'); $this->assertEquals(array(0, 0, 0, 0, 0, 1), $this->getLevels($traces)); }
/** * @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 register(Container $app) { /** * Holds information about the current request * * @return RequestContext */ $app['request_context'] = function () use($app) { $context = new RequestContext(); // set default http & https ports if not set $context->setHttpPort(isset($app['request.http_port']) ? $app['request.http_port'] : 80); $context->setHttpsPort(isset($app['request.https_port']) ? $app['request.https_port'] : 443); return $context; }; /** * Matches URL based on a set of routes. * * @return UrlMatcher */ $app['matcher'] = function () use($app) { return new UrlMatcher($app['router'], $app['request_context']); }; /** * Router */ $options = array('cache_dir' => true === $app['use_cache'] ? __DIR__ . '/' . self::CACHE_DIRECTORY : null, 'debug' => true); $app['router'] = function () use($app, $options) { $router = new Router($app['config.loader'], sprintf(self::CONFIG_ROUTES_FILE, $app['env']), $options); return $router->getRouteCollection(); }; }
public function testRedirectWhenNoSlash() { $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); $matcher = new RedirectableUrlMatcher($coll, $context = new RequestContext()); $this->assertEquals(array('_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction', 'path' => '/foo/', 'permanent' => true, 'scheme' => null, 'httpPort' => $context->getHttpPort(), 'httpsPort' => $context->getHttpsPort(), '_route' => null), $matcher->match('/foo')); }
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; }
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; }
/** * @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 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; }
/** * @return RequestContext */ public function getContext() { if (!$this->context) { $this->context = new RequestContext(); $this->context->fromRequest(\Request::getInstance()); } return $this->context; }
/** * {@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; }
/** * 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); }
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); }
/** * {@inheritdoc} */ public function getContext() { if (!isset($this->context)) { $this->context = new RequestContext(); $this->context->fromRequest($this->request); } return $this->context; }
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()); }
public function buildContext(RequestContext $context) { $context->setScheme($this->scheme); if ($this->host && trim($this->host) !== '') { $context->setHost($this->host); } parent::setContext($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; }
/** * @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)); }
/** * 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; }
/** * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException */ public function testRedirectWhenNoSlashForNonSafeMethod() { $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); $context = new RequestContext(); $context->setMethod('POST'); $matcher = $this->getMockForAbstractClass('Symfony\\Component\\Routing\\Matcher\\RedirectableUrlMatcher', array($coll, $context)); $matcher->match('/foo'); }
public function testHttpRoutes() { $client = self::createClient(); $router = $client->getContainer()->get('router'); $context = new RequestContext(); $context->setMethod('POST'); $router->setContext($context); $router->match('/test/'); }
/** * 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); }
/** * @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); }
/** * 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; }
public function process(Document $document, $type) { $url = $document->getUrl(); $baseUrl = $this->requestContext->getBaseUrl(); if (empty($baseUrl) || strpos($url, $baseUrl) !== 0) { return; } $url = substr($url, strlen($baseUrl)); $document->setUrl($url); }