/**
  * 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);
     }
 }
 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'));
 }
Пример #3
0
 protected function getRoute()
 {
     $routeConfig = $this->application->getConfig('routes');
     $context = new RequestContext('/');
     $matcher = new UrlMatcher($routeConfig, $context);
     return $matcher->match($_SERVER['REQUEST_URI']);
 }
Пример #4
0
 /**
  * @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;
 }
Пример #5
0
 /**
  * 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;
 }
Пример #6
0
 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;
 }
Пример #8
0
 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();
         }
     }
 }
Пример #9
0
 /**
  * @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;
 }
Пример #10
0
 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);
     }
 }
Пример #11
0
 /**
  * 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;
 }
Пример #12
0
 /**
  * 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;
 }
Пример #13
0
 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());
     $this->assertEquals(false, $matcher->match('/no-match'));
     $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 "metod" is ignore if no method is given in the context
     $collection = new RouteCollection();
     $collection->add('foo', new Route('/foo', array(), array('_method' => 'GET|head')));
     // route matches with no context
     $matcher = new UrlMatcher($collection, array(), array());
     $this->assertNotEquals(false, $matcher->match('/foo'));
     // route does not match with POST method context
     $matcher = new UrlMatcher($collection, array('method' => 'POST'), array());
     $this->assertEquals(false, $matcher->match('/foo'));
     // route does match with GET or HEAD method context
     $matcher = new UrlMatcher($collection, array('method' => 'GET'), array());
     $this->assertNotEquals(false, $matcher->match('/foo'));
     $matcher = new UrlMatcher($collection, array('method' => 'HEAD'), array());
     $this->assertNotEquals(false, $matcher->match('/foo'));
 }
Пример #14
0
 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());
 }
Пример #15
0
 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);
 }
Пример #16
0
 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));
 }
 /**
  * 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);
 }
Пример #18
0
 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.
     }
 }
Пример #19
0
 /**
  * @return Response
  * @throws \Exception
  */
 public function match()
 {
     $request = Request::createFromGlobals();
     if (!$request->hasSession()) {
         $session = new Session();
         $request->setSession($session);
         $request->getSession()->start();
     }
     $requestContext = new RequestContext();
     $requestContext->fromRequest($request);
     $matcher = new UrlMatcher($this->routes, $requestContext);
     $parameters = $matcher->match($request->getPathInfo());
     $this->security->configure($request);
     $response = $this->security->accessCheck($request->getPathInfo());
     if ($response) {
         $parameters = $matcher->match($response);
     }
     //var_dump(extract($matcher->match($request->getPathInfo()), EXTR_SKIP)); die('oki');
     $parametersController = explode("::", $parameters['_controller']);
     $controllerName = $parametersController[0];
     $actionName = $parametersController[1];
     $namespace = "app\\controller\\" . $controllerName;
     $controller = new $namespace($requestContext, $this->routes, $request, $this->mode);
     $action = $actionName . 'Action';
     $request->attributes->add($parameters);
     $response = $controller->{$action}($request);
     if (!$response instanceof Response) {
         if ($this->mode == 'dev') {
             try {
                 throw new \Exception('Le controller doit renvoyer une réponse (Symfony\\Component\\HttpFoundation\\Response)', 500);
             } catch (\Exception $e) {
                 echo '<br />' . $e;
             }
         } else {
             return $controller->render('erreur_500.php');
         }
     } else {
         $response->send();
     }
     //return $response;
 }
Пример #20
0
 /**
  * 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();
     }
 }
Пример #21
0
 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;
     }
 }
Пример #23
0
 /**
  * @param Request $request
  * @return Response
  */
 public function handle(Request $request)
 {
     try {
         $request->attributes->add($this->matcher->match($request->getPathInfo()));
         $session = new Session(new NativeSessionStorage(array('cookie_lifetime' => 60 * 60)));
         $session->start();
         $request->setSession($session);
         $controllerParams = $this->resolver->getController($request);
         $arguments = $this->resolver->getArguments($request, $controllerParams);
         /** @var Controller $controller */
         $controller = $controllerParams[0];
         $controller->setContainer($this->container);
         $response = call_user_func_array($controllerParams, $arguments);
         $this->dispatcher->dispatch('post.controller', new ResponseEvent($session));
         return $response;
     } catch (ResourceNotFoundException $e) {
         return new Response('Not Found', 404);
     } catch (\Exception $e) {
         return new Response('An error occurred', 500);
     }
 }
Пример #24
0
 /**
  * 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;
 }
Пример #25
0
 /**
  * @param string $pathInfo
  *
  * @return array
  */
 public function match($pathInfo)
 {
     $host = strtr($this->context->getHost(), '.', '_');
     $method = strtolower($this->context->getMethod());
     $key = 'route_' . $method . '_' . $host . '_' . $pathInfo;
     if ($this->cache->hasItem($key)) {
         return $this->cache->getItem($key)->get();
     }
     $match = parent::match($pathInfo);
     $item = $this->cache->getItem($key);
     $item->set($match)->expiresAfter(self::CACHE_LIFETIME);
     return $match;
 }
Пример #26
0
 /**
  * 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;
 }
Пример #27
0
 /**
  * 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));
 }
Пример #28
0
 /**
  * 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();
     $defaults = array();
     $allow = array();
     $route = null;
     foreach ($this->denormalizeValues($_SERVER) as $key => $value) {
         $name = $key;
         // skip non-routing variables
         // this improves performance when $_SERVER contains many usual
         // variables like HTTP_*, DOCUMENT_ROOT, REQUEST_URI, ...
         if (false === strpos($name, '_ROUTING_')) {
             continue;
         }
         while (0 === strpos($name, 'REDIRECT_')) {
             $name = substr($name, 9);
         }
         // expect _ROUTING_<type>_<name>
         // or _ROUTING_<type>
         if (0 !== strpos($name, '_ROUTING_')) {
             continue;
         }
         if (false !== ($pos = strpos($name, '_', 9))) {
             $type = substr($name, 9, $pos - 9);
             $name = substr($name, $pos + 1);
         } else {
             $type = substr($name, 9);
         }
         if ('param' === $type) {
             if ('' !== $value) {
                 $parameters[$name] = $value;
             }
         } elseif ('default' === $type) {
             $defaults[$name] = $value;
         } elseif ('route' === $type) {
             $route = $value;
         } elseif ('allow' === $type) {
             $allow[] = $name;
         }
         unset($_SERVER[$key]);
     }
     if (null !== $route) {
         $parameters['_route'] = $route;
         return $this->mergeDefaults($parameters, $defaults);
     } elseif (0 < count($allow)) {
         throw new MethodNotAllowedException($allow);
     } else {
         return parent::match($pathinfo);
     }
 }
Пример #29
0
 /**
  * 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;
 }
Пример #30
0
 /**
  * Tries to match a URL based on Apache mod_rewrite matching.
  *
  * Returns false if no route matches the URL.
  *
  * @param  string $url URL to be parsed
  *
  * @return array|false An array of parameters or false if no route matches
  */
 public function match($url)
 {
     if (!isset($_SERVER['_ROUTING__route'])) {
         // fall-back to the default UrlMatcher
         return parent::match($url);
     }
     $parameters = array();
     foreach ($_SERVER as $key => $value) {
         if ('_ROUTING_' === substr($key, 0, 9)) {
             $parameters[substr($key, 9)] = $value;
             unset($_SERVER[$key]);
         }
     }
     return $parameters;
 }