Example #1
0
 public function testDatasRoute()
 {
     $router = new \Router();
     $router->datas('/', 'Tests\\TestController', 'getPost');
     $this->assertEquals('getPost', $router->search('GET', '/'));
     $this->assertEquals('getPost', $router->search('POST', '/'));
 }
Example #2
0
 /**
  * 开始
  * 
  */
 public function run()
 {
     if ('rewrite' == $this->_router->getRouteType()) {
         $this->uriToParams($this->_router->getUriArray());
     }
     $this->dispatch();
 }
Example #3
0
 public function getRouter()
 {
     $router = new Router();
     foreach ($this->getActionRoutes() as $methodRoute) {
         list($route, $methodName) = $methodRoute;
         $method = new \ReflectionMethod($this, $methodName);
         $httpMethod = 'GET';
         $hasRoute = false;
         if ($comment = $method->getDocComment()) {
             if (preg_match('~^[\\s*]*\\@method\\s([^\\s]+)~im', $comment, $match)) {
                 $httpMethod = trim(strtoupper(array_pop($match)));
             }
             if (preg_match('~^[\\s*]*\\@route\\s([^\\s]+)~im', $comment, $match)) {
                 $route = trim(array_pop($match));
                 $hasRoute = true;
             }
         }
         if (!$hasRoute) {
             foreach ($method->getParameters() as $parameter) {
                 $route .= '/{' . ($parameter->isOptional() ? '?' : '') . $parameter->getName() . '}';
             }
         }
         $router->add($httpMethod, $route, [get_class($this), $methodName]);
     }
     return $router;
 }
Example #4
0
	function start () {
		
		// Output-buffering: ON
		ob_start();
		
		// Pre-view middleware
		// ### TODO ###
		
		// Use the Router to map the command string to a view
		try {
			$router = new Router($this->routes, $this->command);
			$router->start();
		}
		catch (Http404Exception $e) {
			return self::http_404($e->getMessage());
		}
		catch (Exception $e) {
			return self::http_500($e->getMessage());
		}
		
		// Post-view middleware
		// ### TODO ###
		
		// Output-buffering: Flush
		ob_end_flush();
		
	}
 protected function setParams()
 {
     global $routes;
     $do = $this->request->get('do', '');
     unset($this->request->get['do']);
     unset($this->request->request['do']);
     if (!empty($do) && (preg_match('/^(?P<lang>[a-zA-Z]{2})\\/(?P<target>[a-zA-Z0-9]+)\\/(?P<action>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<lang>[a-zA-Z]{2})\\/(?P<target>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<target>[a-zA-Z0-9]{3,})\\/(?P<action>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<target>[a-zA-Z0-9]{3,})\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<lang>[a-zA-Z]{2})\\/?$/', $do, $matches))) {
     }
     $lang = !empty($matches['lang']) ? $matches['lang'] : '';
     $this->target = !empty($matches['target']) ? $matches['target'] : DEFAULT_CONTROLLER_TARGET;
     $this->action = !empty($matches['action']) ? $matches['action'] : DEFAULT_CONTROLLER_ACTION;
     $this->params = !empty($matches['params']) ? explode('/', $matches['params']) : array();
     $router = new Router($lang, $routes);
     $router->dispatch($this);
     $this->route = $this->target . '/' . $this->action . '/' . implode('/', $this->params);
     $this->uri = ROOT_HTTP . $this->target . '/' . $this->action . '/';
     if (empty($lang)) {
         $lang = Lang::getDefaultLang();
     }
     $this->lang = new Lang($lang);
     $this->querystring = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
     $this->querystring = (!empty($this->querystring) ? '?' : '') . $this->querystring;
     if (get_magic_quotes_gpc()) {
         $this->request = Utils::stripslashes($this->request);
         $this->post = Utils::stripslashes($this->post);
         $this->get = Utils::stripslashes($this->get);
     }
     $this->session = !SESSION_DISABLED ? Session::getInstance(SESSION_DEFAULT_NAME) : null;
 }
Example #6
0
 public function getController()
 {
     $Router = new Router();
     $this->Router = $Router;
     $xml = new \DOMDocument();
     $xml->load(__DIR__ . '/../../App/' . $this->name . '/Config/routes.xml');
     $routes = $xml->getElementsByTagName('route');
     // On parcourt les routes du fichier XML.
     foreach ($routes as $route) {
         $vars = [];
         // On regarde si des variables sont présentes dans l'URL.
         if ($route->hasAttribute('vars')) {
             $vars = explode(',', $route->getAttribute('vars'));
         }
         // On ajoute la route au routeur.
         $Router->addRoute(new Route($route->getAttribute('url'), $route->getAttribute('module'), $route->getAttribute('action'), $vars));
     }
     try {
         // On récupère la route correspondante à l'URL.
         $matchedRoute = $Router->getRoute($this->httpRequest->requestURI());
     } catch (\RuntimeException $e) {
         if ($e->getCode() == Router::NO_ROUTE) {
             // Si aucune route ne correspond, c'est que la page demandée n'existe pas.
             $this->httpResponse->redirect404();
         }
     }
     // On ajoute les variables de l'URL au tableau $_GET.
     $_GET = array_merge($_GET, $matchedRoute->vars());
     // On instancie le contrôleur.
     $controllerClass = 'App\\' . $this->name . '\\Modules\\' . $matchedRoute->module() . '\\' . $matchedRoute->module() . 'Controller';
     return new $controllerClass($this, $matchedRoute->module(), $matchedRoute->action());
 }
Example #7
0
 public function route($model, $form, $fieldName, $fieldType, $path)
 {
     $field = $form->fields()->{$fieldName};
     if (!$field or $field->type() !== $fieldType) {
         throw new Exception('Invalid field');
     }
     $routes = $field->routes();
     $router = new Router($routes);
     if ($route = $router->run($path)) {
         if (is_callable($route->action()) and is_a($route->action(), 'Closure')) {
             return call($route->action(), $route->arguments());
         } else {
             $controllerFile = $field->root() . DS . 'controller.php';
             $controllerName = $fieldType . 'FieldController';
             if (!file_exists($controllerFile)) {
                 throw new Exception(l('fields.error.missing.controller'));
             }
             require_once $controllerFile;
             if (!class_exists($controllerName)) {
                 throw new Exception(l('fields.error.missing.class'));
             }
             $controller = new $controllerName($model, $field);
             return call(array($controller, $route->action()), $route->arguments());
         }
     } else {
         throw new Exception(l('fields.error.route.invalid'));
     }
 }
Example #8
0
 /**
  * @dataProvider testEqualsProvider
  */
 function testEquals($method, $val)
 {
     $r = new Router();
     $r->initNoCall();
     $call = call_user_func([$r, $method]);
     $this->assertEquals($val, $call, _unit_dump(['method' => $method, 'expected' => $val, 'actual' => $call]));
 }
 public function testSpeedRegexRoutes()
 {
     $start = microtime(1);
     $router = new Router();
     $router->addRouteRule(new RouteRule("show/<d>", "show/<d>"));
     $end = microtime(1) - $start;
     echo sprintf('Initialize  %8d rules at %f sec, per 1 rule %0.20f sec', 1, $end, $end / 1), PHP_EOL;
     $start = microtime(1);
     $data = serialize($router);
     $end = microtime(1) - $start;
     echo sprintf('Serialize   %8d rules at %f sec, per 1 rule %0.20f sec', 1, $end, $end / 1), PHP_EOL;
     $start = microtime(1);
     unserialize($data);
     $end = microtime(1) - $start;
     echo sprintf('Unserialize %8d rules at %f sec, per 1 rule %0.20f sec', 1, $end, $end / 1), PHP_EOL;
     $count = 1000;
     $start = microtime(1);
     for ($i = 0; $i < $count; $i++) {
         $router->createUrl("show/{$i}");
     }
     $end = microtime(1) - $start;
     echo sprintf('Create      %8d urls  at %f sec, per 1 call %0.20f sec', $count, $end, $end / $count), PHP_EOL;
     $start = microtime(1);
     for ($i = 0; $i < $count; $i++) {
         $router->matchUrl("show/{$i}");
     }
     $end = microtime(1) - $start;
     echo sprintf('Found       %8d urls  at %f sec, per 1 call %0.20f sec', $count, $end, $end / $count), PHP_EOL;
 }
Example #10
0
 public static function isAllowedUrl($url)
 {
     include SYS_APPLICATION_PATH . DS . 'config' . DS . 'routes.php';
     $route = new \Router($routes, '/index.php', $url);
     $structure = $route->getCallStructure();
     return self::isAllowed($structure['controller'], $structure['action'], $structure['parms']);
 }
Example #11
0
 public static function run()
 {
     session_start();
     $router = new Router();
     list($controller, $action, $mergedParams) = $router->parse();
     return $router->dispatch($controller, $action, $mergedParams);
 }
Example #12
0
 function run()
 {
     $router = new Router();
     try {
         /** @var RouterResult $result */
         $result = $router->process($this->config['routes']);
         $actionName = $result->getActionName();
         $controllerName = $result->getControllerName();
         $params = $result->getParams();
         /** @var Controller $controller */
         $controller = new $controllerName();
         $controller->setParams($params);
         if ($controller instanceof \Framework\Config\ConfigAwareInterface) {
             $controller->setConfig($this->config);
         }
         $viewData = $controller->{$actionName}();
         if ($controller->getUseTemplate() == true) {
             $template = $result->getController() . '/' . $result->getAction();
             $useLayout = $controller->getUseLayout();
             $view = new View();
             $view->display($viewData, $template, $useLayout);
         }
     } catch (Exception\NotFoundException $e) {
         header("HTTP/1.0 404 Not Found");
         $message = $this->config['environment'] === \Framework\App::DEVELOPMENT_ENVIRONMENT ? 'Page Not Found' : $e->getMessage();
         $view = new View();
         $view->display(['message' => $message], 'error/error');
     } catch (Exception\BaseException $e) {
         header("HTTP/1.0 500 Internal Server Error");
         $message = $this->config['environment'] === \Framework\App::DEVELOPMENT_ENVIRONMENT ? 'Internal Server Error' : $e->getMessage();
         $view = new View();
         $view->display(['message' => $message], 'error/error');
     }
 }
Example #13
0
 function __construct()
 {
     $sesion = new Sesion('usuario');
     $router = new Router();
     $router->AppRoutes();
     $router->View($sesion);
 }
Example #14
0
 /**
  * Bese controller constructor: restores user object by using session data and
  * checks a permission to a requested action
  *
  * @param LiveCart $application Application instance
  * @throws AccessDeniedExeption
  */
 public function __construct(LiveCart $application)
 {
     parent::__construct($application);
     $this->router = $this->application->getRouter();
     if (!$application->isInstalled() && !$this instanceof InstallController) {
         header('Location: ' . $this->router->createUrl(array('controller' => 'install', 'action' => 'index')));
         exit;
     }
     unset($this->locale);
     unset($this->config);
     unset($this->user);
     unset($this->session);
     $this->checkAccess();
     $this->application->setRequestLanguage($this->request->get('requestLanguage'));
     $this->configFiles = $this->getConfigFiles();
     $this->application->setConfigFiles($this->configFiles);
     $localeCode = $this->application->getLocaleCode();
     // add language code to URL for non-default languages
     if ($localeCode != $this->application->getDefaultLanguageCode()) {
         $this->router->setAutoAppendVariables(array('requestLanguage' => $localeCode));
     }
     // verify that the action is accessed via HTTPS if it is required
     if ($this->router->isSSL($this->request->getControllerName(), $this->request->getActionName()) && !$this->router->isHttps()) {
         header('Location: ' . $this->router->createFullUrl($_SERVER['REQUEST_URI'], true));
         exit;
     }
 }
Example #15
0
 public function testFindMatch()
 {
     $pattern = 'admin/edit/:id';
     $router = new Router();
     $this->assertEquals($router->findMatch($pattern, 'admin/edit/1'), true);
     $this->assertEquals($router->findMatch($pattern, 'admin/create/1'), false);
 }
Example #16
0
 public function getController()
 {
     $router = new Router();
     $xml = new \DOMDocument();
     $xml->load(__DIR__ . '/../../App/' . $this->name . '/Config/route.xml');
     $routes = $xml->getElementByTagName("route");
     foreach ($routes as $route) {
         $vars = [];
         if ($route->hasAttribute('vars')) {
             $vars = explode(',', $route->getAttribute('vars'));
         }
         $router->addRoute(new Route($route->getAttribute('url'), $route->getAttribute('module'), $route->getAttribute('action'), $vars));
     }
     try {
         $matched_route = $router->getRoute($this->httpRequest->requestURI());
     } catch (\RuntimeException $exception) {
         if ($exception->getCode() == Router::NO_ROUTE) {
             $this->httpResponse->redirect404();
         }
     }
     // Add variables in tab: $_GET
     $_GET = array_merge($_GET, $matched_route->module(), $matched_route->action());
     // Instancie the controller
     $controller_class = 'App\\' . $this->name . '\\Modules\\' . $matched_route->module() . '\\' . $matched_route->module() . 'Controllers';
     return new $controller_class($this, $matched_route->module(), $matched_route->action());
 }
 public function generateResponse($route = null, $params = array(), $internal = false)
 {
     $router = new Router();
     $request = Request::getInstance();
     $request->setInternal($internal);
     if ($route) {
         $route = $router->getRoute($route);
     } else {
         $route = $router->getDefaultRoute();
     }
     $controller = $route->getController();
     $action = $route->getAction();
     $controller = new $controller();
     $r = new ReflectionMethod($controller, $action);
     $paramsOfFunction = $r->getParameters();
     $paramsToPass = array();
     $indexParams = 0;
     foreach ($paramsOfFunction as $param) {
         if ($param->getClass() != NULL && $param->getClass()->getName() == 'Request') {
             $paramsToPass[] = $request;
         } else {
             if (isset($params[$indexParams])) {
                 $paramsToPass[] = $params[$indexParams++];
             } else {
                 $paramsToPass[] = null;
             }
         }
     }
     if (!empty($paramsToPass)) {
         return call_user_func_array(array($controller, $action), $paramsToPass);
     }
     return $controller->{$action}();
 }
 /**
  * Add all the routes in the router in parameter
  * @param $router Router
  */
 public function generateRoute(Router $router)
 {
     foreach ($this->classes as $class) {
         $classMethods = get_class_methods($this->namespace . $class . 'Controller');
         $rc = new \ReflectionClass($this->namespace . $class . 'Controller');
         $parent = $rc->getParentClass();
         $parent = get_class_methods($parent->name);
         $className = $this->namespace . $class . 'Controller';
         foreach ($classMethods as $methodName) {
             if (in_array($methodName, $parent) || $methodName == 'index') {
                 continue;
             } else {
                 foreach (Router::getSupportedHttpMethods() as $httpMethod) {
                     if (strstr($methodName, $httpMethod)) {
                         continue 2;
                     }
                     if (in_array($methodName . $httpMethod, $classMethods)) {
                         $router->add('/' . strtolower($class) . '/' . $methodName, new $className(), $methodName . $httpMethod, $httpMethod);
                         unset($classMethods[$methodName . $httpMethod]);
                     }
                 }
                 $router->add('/' . strtolower($class) . '/' . $methodName, new $className(), $methodName);
             }
         }
         $router->add('/' . strtolower($class), new $className(), 'index');
     }
 }
Example #19
0
 public function start()
 {
     $s = new Settings();
     $r = new Router();
     $r->load_controller();
     $r->load_action();
 }
 /**
  * It processes the request and connects the necessary classes and methods
  * @access public
  * @static
  * @return void
  */
 public static function run()
 {
     require_once ROOT . '/core/Loader.php';
     $autoload = new Loader();
     $registry = Registry::getInstance();
     $router = new Router($registry->getObject('request'));
     $router->init();
 }
Example #21
0
 /**
  *	Router elindítása
  */
 private function load_router()
 {
     $router = new Router();
     $router->find($this->registry->uri_path, $this->registry->area);
     $this->registry->controller = $router->controller;
     $this->registry->action = $router->action;
     $this->registry->params = $router->params;
 }
 public function testExecuteRoute()
 {
     $Router = new Router(array());
     $route = $Router->parseRoute();
     $Router->executeRoute($route);
     $this->assertEquals($Router->controller->calledAction, 'util');
     $this->assertEquals($Router->controller->actionParams, array('router'));
 }
Example #23
0
 protected function getContent(Router $router, Context $context, Route $route)
 {
     $callback = $route->getAction();
     $values = $router->extract($context, $route);
     $bindings = $router->bind($values, $route->getBindings());
     $arguments = $router->buildArguments($callback, $bindings);
     return $callback(...$arguments);
 }
Example #24
0
 public static function recognize(Request $request, ContextManager $context)
 {
     // XXX: request URI hack, for medick installation in subfolders (e.g. `medick2` as base)
     // XXX: test with other servers and other types of PHP installations
     // $request->uri= substr($request->uri, strlen($context->config()->property('base', true)));
     $router = new Router($context->map()->find_route($request), $context);
     return $router->create_controller($request);
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function send(Message $message)
 {
     $queueName = $this->router->queueFor($message);
     if (!$queueName) {
         throw new Exception\QueueNotFound(sprintf('Could not find a queue for "%s"', $message->getName()));
     }
     $this->driver->enqueue($queueName, $message);
 }
Example #26
0
 /**
  * Display the IDE configuration
  */
 public function getIDEConfiguration()
 {
     $datasBridge = $this->bridge->getIDEConfiguration();
     $datasRouter = $this->router->getIDEConfiguration();
     $datas = array('tuleapRestApiBridgeRootUrl' => $datasBridge['tuleapRestApiBridgeRootUrl'], 'tuleapRestApiBridgeBaseUrl' => $datasBridge['tuleapRestApiBridgeBaseUrl'], 'tuleapRestApiBridgeHasRedirectBase' => $datasBridge['tuleapRestApiBridgeHasRedirectBase'], 'tuleapRestApiBridgeHasRedirectBaseManualConfig' => $datasBridge['tuleapRestApiBridgeHasRedirectBaseManualConfig'], 'getUserTokenRoute' => $datasRouter['getUserToken'], 'getArtifactsListRoute' => $datasRouter['getArtifactsList'], 'getArtifactRoute' => $datasRouter['getArtifact'], 'getIDEConfigurationRoute' => $datasRouter['getIDEConfiguration']);
     $viewServiceProvider = new ViewServiceProvider();
     $viewServiceProvider->render(__DIR__ . '/Ressources/Views/config-ide.phtml', $datas);
 }
Example #27
0
 /**
  * Create a Router
  *
  * @return \mostofreddy\ruta\Router
  */
 public function newInstance()
 {
     $o = new Router();
     $collection = new RouteCollection();
     $collection->routeFactory(new RouteFactory());
     $o->routeCollection($collection);
     return $o;
 }
Example #28
0
 /**
  * This method launches the application.
  */
 public function run()
 {
     $router = new Router($this);
     $controller = $router->getController();
     $controller->execute();
     $this->response->setPage($controller->getPage());
     $this->response->send();
 }
Example #29
0
 /**
  *  T' the high seas! Garrr!
  */
 public function setSail()
 {
     $request = new Request($_GET, $_POST, $_COOKIE, $_SERVER);
     $router = new Router($request);
     $response = new Response();
     $dispatcher = new Dispatcher($router->dispatch(), $response);
     $dispatcher->fireCannons();
 }
 /**
  * @covers FrontController::__construct
  * @covers FrontController::dispatch
  */
 public function testDispatchingWorksCorrectly()
 {
     $request = new Request(array('REQUEST_URI' => '/test'));
     $response = new Response();
     $router = new Router();
     $router->set('test', 'TestController');
     $frontController = new FrontController($request, $response, $router, new ControllerFactory(new MapperFactory(new PDO('sqlite::memory:'))), new ViewFactory());
     $this->assertInstanceOf('TestView', $frontController->dispatch($router));
 }