/** * Run Application. */ public function run() { if (empty($this['request'])) { $this['request'] = Request::createFromGlobals(); } $routes = $this['routes']; $request = $this['request']; $context = $this['requestContext']; $context->fromRequest($this['request']); $matcher = new UrlMatcher($routes, $context); $resolver = new ControllerResolver(); try { $request->attributes->add($matcher->match($request->getPathInfo())); $controller = $resolver->getController($request); $arguments = $resolver->getArguments($request, $controller); if (is_array($controller) && $controller[0] instanceof BaseController) { $controller[0]->setRequest($request); $controller[0]->setApplication($this); } $response = call_user_func_array($controller, $arguments); } catch (ResourceNotFoundException $e) { $response = new Response('Not Found', 404); } catch (\Exception $e) { $response = new Response('An error occurred', 500); } return $response; }
protected function getRoute() { $routeConfig = $this->application->getConfig('routes'); $context = new RequestContext('/'); $matcher = new UrlMatcher($routeConfig, $context); return $matcher->match($_SERVER['REQUEST_URI']); }
/** * @param boolean $bool * @param \WP $wp */ public function dispatch($bool, \WP $wp) { // get path info after domain part of the URL $pathinfo = $this->request->getPathInfo(); // try to match for stored routes $context = new RequestContext('/'); $matcher = new UrlMatcher($this->routes, $context); try { $parameters = $matcher->match($pathinfo); // without WordPress theme around if ('basic_output' == $parameters['type']) { $parameters['handler']($this->request, $parameters); $this->handleExit(); // with WordPress theme around } elseif ('page' == $parameters['type']) { do_action('parse_request', $wp); $this->setupQuery($parameters['page'], $this->request, $parameters); do_action('wp', $wp); $this->loader->load(); $this->handleExit(); } } catch (ResourceNotFoundException $e) { // route not found. we dont bother for now, because the request will be handled by WordPress which will show // something like a page not found page. } return $bool; }
public function testMatch() { // test the patterns are matched are parameters are returned $collection = new RouteCollection(); $collection->add('foo', new Route('/foo/{bar}')); $matcher = new UrlMatcher($collection, array(), array()); try { $matcher->match('/no-match'); $this->fail(); } catch (NotFoundException $e) { } $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz'), $matcher->match('/foo/baz')); // test that defaults are merged $collection = new RouteCollection(); $collection->add('foo', new Route('/foo/{bar}', array('def' => 'test'))); $matcher = new UrlMatcher($collection, array(), array()); $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz', 'def' => 'test'), $matcher->match('/foo/baz')); // test that route "method" is ignored if no method is given in the context $collection = new RouteCollection(); $collection->add('foo', new Route('/foo', array(), array('_method' => 'GET|head'))); $matcher = new UrlMatcher($collection, array(), array()); $this->assertInternalType('array', $matcher->match('/foo')); // route does not match with POST method context $matcher = new UrlMatcher($collection, array('method' => 'POST'), array()); try { $matcher->match('/foo'); $this->fail(); } catch (MethodNotAllowedException $e) { } // route does match with GET or HEAD method context $matcher = new UrlMatcher($collection, array('method' => 'GET'), array()); $this->assertInternalType('array', $matcher->match('/foo')); $matcher = new UrlMatcher($collection, array('method' => 'HEAD'), array()); $this->assertInternalType('array', $matcher->match('/foo')); }
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(); } } }
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 string $pathinfo * * @return array */ public function match($pathinfo) { $urlMatcher = new UrlMatcher($this->getRouteCollection(), $this->getContext()); $result = $urlMatcher->match($pathinfo); if (!empty($result)) { // Remap locale for front-end requests if ($this->isMultiDomainHost() && $this->isMultiLanguage() && !$result['preview']) { $localeMap = $this->getLocaleMap(); $locale = $result['_locale']; $result['_request_locale'] = $locale; $result['_locale'] = $localeMap[$locale]; } // Add extra parameters to parameter bag $extraData = $this->domainConfiguration->getExtraData(); if (!empty($extraData)) { $result['_extra'] = $extraData; } $nodeTranslation = $this->getNodeTranslation($result); if (is_null($nodeTranslation)) { throw new ResourceNotFoundException('No page found for slug ' . $pathinfo); } $result['_nodeTranslation'] = $nodeTranslation; } return $result; }
/** * Tries to match a URL path with a set of routes. * * If the matcher can not find information, it must throw one of the * exceptions documented below. * * @param string $pathinfo The path info to be parsed (raw format, i.e. not * urldecoded) * * @return array An array of parameters * * @throws ResourceNotFoundException If the resource could not be found * @throws MethodNotAllowedException If the resource was found but the * request method is not allowed */ public function match($pathinfo) { $urlMatcher = new UrlMatcher($this->routeCollection, $this->getContext()); $result = $urlMatcher->match($pathinfo); if (!empty($result)) { try { // The route matches, now check if it actually exists $result['content'] = $this->contentManager->findActiveBySlug($result['slug']); } catch (NoResultException $e) { try { //is it directory index if (substr($result['slug'], -1) == '/' || $result['slug'] == '') { $result['content'] = $this->contentManager->findActiveBySlug($result['slug'] . 'index'); } else { if ($this->contentManager->findActiveBySlug($result['slug'] . '/index')) { $redirect = new RedirectResponse($this->request->getBaseUrl() . "/" . $result['slug'] . '/'); $redirect->sendHeaders(); exit; } } } catch (NoResultException $ex) { try { $result['content'] = $this->contentManager->findActiveByAlias($result['slug']); } catch (NoResultException $ex) { throw new ResourceNotFoundException('No page found for slug ' . $pathinfo); } } } } return $result; }
/** * @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; }
function run() { $routes = new RouteCollection(); foreach ($this->serviceManager->get('ConfigManager')->getConfig('routes') as $rota => $values) { $routes->add($rota, new Route($values['route'], array('controller' => $values['controller'], 'action' => $values['action']))); } $context = $this->serviceManager->get('RequestManager')->getContext(); $matcher = new UrlMatcher($routes, $context); $errorController = $this->getServiceManager()->get('ErrorController'); try { $parameters = $matcher->match($context->getPathInfo()); $controller = $this->getServiceManager()->get($parameters['controller']); $action = $this->getNomeAction($parameters['action']); if (false == method_exists($controller, $action)) { throw new Exception(sprintf('O Controller %s não possui o método %s', get_class($controller), $action)); } $actionParameters = $this->getActionParameters($parameters); if (true == method_exists($controller, 'beforeDispatch')) { call_user_func(array($controller, 'beforeDispatch')); } return call_user_func_array(array($controller, $action), $actionParameters); } catch (ResourceNotFoundException $ex) { return $errorController->actionError404(); } catch (MethodNotAllowedException $ex) { return $errorController->actionError500($ex); } catch (Exception $ex) { return $errorController->actionError500($ex); } }
/** * Run Application. */ public function run() { $request = $this['request'] = Request::createFromGlobals(); $routes = $this['routes']; $context = $this['request_context']; $context->fromRequest($this['request']); $matcher = new UrlMatcher($routes, $context); $resolver = new ControllerResolver(); try { $request->attributes->add($matcher->match($request->getPathInfo())); $controller = $resolver->getController($request); $arguments = $resolver->getArguments($request, $controller); if (is_array($controller) && $controller[0] instanceof \Task\Controllers\BaseController) { $controller[0]->setRequest($request); $controller[0]->setApplication($this); } $response = call_user_func_array($controller, $arguments); } catch (ResourceNotFoundException $e) { $response = new JsonResponse(["errors" => ["type" => "Not found"]], Response::HTTP_NOT_FOUND); } catch (\Exception $e) { $response = new JsonResponse(["errors" => ["type" => $e->getMessage(), "stacktrace" => $e->getTraceAsString()]], Response::HTTP_INTERNAL_SERVER_ERROR); } $response->headers->set("Access-Control-Allow-Origin", "*"); $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); $response->headers->set("Access-Control-Allow-Headers", "Content-Type"); $response->headers->set("Server", "Test task REST"); return $response; }
public function match($urlOrRequest = null) { $request = $this->makeRequest($urlOrRequest); $matcher = new UrlMatcher($this->getRoutes(), $this->context); $params = $matcher->matchRequest($request); return $this->handler->handle($params, $request); }
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 parseRequest(Event $event) { $request = $event->get('request'); $matcher = new UrlMatcher($this->routes, array('base_url' => $request->getBaseUrl(), 'method' => $request->getMethod(), 'host' => $request->getHost(), 'is_secure' => $request->isSecure())); if (false === ($attributes = $matcher->match($request->getPathInfo()))) { return false; } $request->attributes->add($attributes); }
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)); }
/** * @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); }
/** * Match given urls via the context to the routes we defined. * This functionality re-uses the default Symfony way of routing and its components * * @param string $pathinfo * * @return array */ public function match($pathinfo) { $enableAutodetect = $this->container->getParameter('kunstmaan_language_chooser.autodetectlanguage'); $enableSplashpage = $this->container->getParameter('kunstmaan_language_chooser.showlanguagechooser'); // splashpage AND autodetect are disabled, this request may not be routed if (!$enableSplashpage && !$enableAutodetect) { throw new ResourceNotFoundException('Autodetect and splashpage disabled, can not possibly match.'); } $urlMatcher = new UrlMatcher($this->routeCollection, $this->getContext()); return $urlMatcher->match($pathinfo); }
private function dispatch() { $req = Request::createFromGlobals(); $ctx = new RequestContext(); $ctx->fromRequest($req); $matcher = new UrlMatcher($this->routes, $ctx); $pi = $req->getPathInfo(); try { $match = $matcher->match($pi); $callable = null; $controller = null; $method = null; if (isset($match['callable'])) { $callable = $match['callable']; } if (isset($match['controller'])) { $controller = $match['controller']; $method = $match['method']; } unset($match['callable']); unset($match['_route']); unset($match['controller']); unset($match['method']); $match['request'] = $req; $response = ''; if ($callable) { $invoker = new Invoker(); $response = $invoker->call($callable, $match); } if ($controller) { if (!class_exists($controller)) { $error = new Response('Invalid method', 501); $error->send(); die; } $controllerInst = new $controller($this->context); $response = call_user_func_array([$controllerInst, $method], array_values($match)); } if (is_object($response) && $response instanceof Response) { $response->send(); } else { if (is_string($response)) { echo $response; } } die; } catch (MethodNotAllowedException $mex) { // let wordpress continue doing what it does. $response = new Response('Method not allowed', 405); $response->send(); } catch (ResourceNotFoundException $ex) { // let wordpress continue doing what it does. } }
/** * Handles request event * * @param HttpRequestEvent $event * * @throws NotFoundHttpException */ public function onRequest(HttpRequestEvent $event) { $event->getResponse()->getHeaders()->set('X-Powered-By', 'ThinFrame/Karma (v0.2, engine ReactPHP)'); $matcher = new UrlMatcher($this->routeCollection, new RequestContext('', $event->getRequest()->getMethod())); try { $route = $matcher->match($event->getRequest()->getPath()); $this->handleRoute($route, $event->getRequest(), $event->getResponse()); $event->stopPropagation(); } catch (ResourceNotFoundException $exception) { throw new NotFoundHttpException(); } }
public function match() { $context = new RequestContext(); $context->fromRequest($this->app->request()); $matcher = new UrlMatcher($this->routes, $context); try { $parameters = $matcher->match($this->app->request()->getPathInfo()); } catch (Exception $e) { $parameters = array(); } return $parameters; }
/** * @return array|bool */ public function matchCurrentRoute() { $context = new RequestContext(); $matcher = new UrlMatcher($this->routes, $context); $request = new CakeRequest(); try { return $matcher->match($request->here()); } catch (Exception $e) { //route is not registered in yml file return false; } }
public final function matchRoute(\bolt\browser\route $route, \bolt\browser\request $req) { $collection = b::browser('route\\collection\\create', [$route]); $match = new UrlMatcher($collection, $req->getContext()); // we're going to try and match our request // if not we fall back to error try { return $match->matchRequest($req); } catch (ResourceNotFoundException $e) { return false; } }
/** * Match given urls via the context to the routes we defined. * This functionality re-uses the default Symfony way of routing and its * components * * @param string $pathinfo * * @throws ResourceNotFoundException * * @return array */ public function match($pathinfo) { $urlMatcher = new UrlMatcher($this->getRouteCollection(), $this->getContext()); $result = $urlMatcher->match($pathinfo); if (!empty($result)) { $nodeTranslation = $this->getNodeTranslation($result); if (is_null($nodeTranslation)) { throw new ResourceNotFoundException('No page found for slug ' . $pathinfo); } $result['_nodeTranslation'] = $nodeTranslation; } return $result; }
/** * Tries to match a URL path with a set of routes. * * If the matcher can not find information, it must throw one of the * exceptions documented below. * * @param string $pathinfo The path info to be parsed (raw format, i.e. not * urldecoded) * * @return array An array of parameters * * @throws ResourceNotFoundException If the resource could not be found */ public function match($pathinfo) { $urlMatcher = new UrlMatcher($this->routeCollection, $this->getContext()); $result = $urlMatcher->match($pathinfo); if (!empty($result)) { $entity = $this->container->get('opifer.crud.slug_transformer')->transform($result['slug']); if (false === $entity) { throw new ResourceNotFoundException('The route ' . $pathinfo . ' is not registered on the CrudBundle.'); } $result['entity'] = $entity; } return $result; }
/** * Automatically generated run method * * @param Request $request * @return Response */ public function run(Request $request) { $prefs = $this->getServiceContainer()->getPreferenceLoader()->getSystemPreferences(); $routes = $this->generateRoutes(); $response = new Response(); $context = new RequestContext($prefs->getAccountUrl()); $matcher = new UrlMatcher($routes, $context); $payload = []; $match = $matcher->match($this->getDestination()); $route = $match['_route']; $module = $this->getModule(); $auth = $this->getServiceContainer()->getAuthManager(); $action = null; switch ($route) { case 'index': if ($auth->isRecognized()) { $action = $module->loadAction('dashboard', 'html'); } else { $action = $module->loadAction('index', 'html'); } break; case 'register': $action = $module->loadAction('register', 'html'); break; case 'forgot-password': case 'forgot-password-token': $action = $module->loadAction('forgot-password', 'html'); $action->setParams(['token' => isset($match['token']) ? $match['token'] : null]); break; case 'login': $action = $module->loadAction('login', 'html'); break; case 'activity': $action = $module->loadAction('activity', 'html'); break; case 'settings': $action = $module->loadAction('settings', 'html'); $action->setParams(['section' => $match['section']]); break; case 'logout': $action = $module->loadAction('logout'); break; } $kernel = $this->getServiceContainer()->getKernel(); $response = $kernel->handle($action, $request); if ($response instanceof RedirectResponse) { return $response; } $payload = ['main' => $response->getContent()]; return $this->responder->run($request, new Blank($payload)); }
/** * Efetua a análise da URL para detectar se houve alguma rota encontrada, caso contrário irá retornar * uma rota para tela de erro. * * @return array * * @todo Por o bloco de verificação dentro de um try...catch pois o match lança excessão caso não encontre rotas se cair no catch retorna rota de erro */ public function match() { $context = new RequestContext(); $context->fromRequest(Request::createFromGlobals()); $matcher = new UrlMatcher($this->collection, $context); try { $parameters = $matcher->match(Request::createFromGlobals()->getPathInfo()); } catch (ResourceNotFoundException $e) { return new Response('caminho_nao_encontrado', 404); } catch (MethodNotAllowedException $e) { return new Response('metodo_nao_permitido', 405); } return $parameters; }
public static function start() { /* Loading preconfigured DataBased */ try { Muffin\System\DataBase::initDB(); } catch (Exception $e) { } /* Catching global variables, also we create the response */ $request = Request::createFromGlobals(); $response = new Response(); /* Loading the routes file and define the routes as the container of the routers definitions More info: http://symfony.com/doc/current/components/routing/introduction.html#load-routes-fr om-a-file */ $resolver = new HttpKernel\Controller\ControllerResolver(); $locator = new FileLocator(array(__DIR__)); $loader = new YamlFileLoader($locator); $routes = $loader->load('config/routes.yml'); $context = new RequestContext($request->getMethod()); try { $matcher = new UrlMatcher($routes, $context); $request->attributes->add($matcher->match($request->getPathInfo())); $controller = $resolver->getController($request); $arguments = $resolver->getArguments($request, $controller); $response = call_user_func_array($controller, $arguments); /* If the path doesn't exits */ } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { $response = new Response('Not Found', 404); } catch (Exception $e) { $response = new Response('An error occurred' . $e, 500); } $response->send(); /* IF we created a connection to the DataBase we close it at the end */ try { Muffin\System\DataBase::close(); } catch (Exception $e) { } }
private function matchRoute() { $routes = new RouteCollection(); foreach ($this->routes as $key => $route) { if (!empty($route['requirements'])) { $routes->add($key, new Route($route['pattern'], $route['defaults'], $route['requirements'])); } else { $routes->add($key, new Route($route['pattern'], $route['defaults'])); } } $context = new RequestContext(); $context->fromRequest($this->request); $matcher = new UrlMatcher($routes, $context); $attributes = $matcher->match($this->request->getPathInfo()); $this->request->attributes->add($attributes); }
/** * Tries to match a URL based on Apache mod_rewrite matching. * * Returns false if no route matches the URL. * * @param string $pathinfo The pathinfo to be parsed * * @return array An array of parameters * * @throws MethodNotAllowedException If the current method is not allowed */ public function match($pathinfo) { $parameters = array(); $allow = array(); $match = false; foreach ($_SERVER as $key => $value) { $name = $key; if (0 === strpos($name, 'REDIRECT_')) { $name = substr($name, 9); } if (0 === strpos($name, '_ROUTING_')) { $name = substr($name, 9); } else { continue; } if ('_route' == $name) { $match = true; } elseif (0 === strpos($name, '_allow_')) { $allow[] = substr($name, 7); } else { $parameters[$name] = $value; } unset($_SERVER[$key]); } if ($match) { return $parameters; } elseif (0 < count($allow)) { throw new MethodNotAllowedException($allow); } else { return parent::match($pathinfo); } }
/** * {@inheritdoc} */ public function match($pathinfo) { $urlMatcher = new UrlMatcher($this->getRouteCollection(), $this->getContext()); $result = $urlMatcher->match($pathinfo); $path = $result['path']; preg_match_all('/{(.*?)}/', $path, $matches); if (!empty($matches) && isset($matches[1])) { foreach ($matches[1] as $match) { if (array_key_exists($match, $result)) { $path = str_replace('{' . $match . '}', $result[$match], $path); } } } $result['path'] = $path; return $result; }