public function testMatchTraversesAllRegisteredRoutesIfFalseIsReturned() { $Request = $this->createRequest(''); $PersonRoute = $this->mock('AkRoute', array('parametrize' => new RouteDoesNotMatchRequestException())); $AuthorRoute = $this->mock('AkRoute', array('parametrize' => true)); $this->Router->addRoute('person', $PersonRoute); $this->Router->addRoute('author', $AuthorRoute); $this->Router->match($Request); $this->assertEqual($AuthorRoute, $this->Router->currentRoute); }
function testMatchTraversesAllRegisteredRoutesIfFalseIsReturned() { $Request = $this->getMock('AkRequest', array(), array(), '', false); $PersonRoute = $this->getMock('AkRoute', array(), array('person/:name')); $PersonRoute->expects($this->once())->method('parametrize')->with($Request)->will($this->throwException(new RouteDoesNotMatchRequestException())); $AuthorRoute = $this->getMock('AkRoute', array(), array('author/:name')); $AuthorRoute->expects($this->once())->method('parametrize')->with($Request)->will($this->returnValue(true)); $this->Router->addRoute('person', $PersonRoute); $this->Router->addRoute('author', $AuthorRoute); $this->Router->match($Request); $this->assertEquals($AuthorRoute, $this->Router->currentRoute); }
/** * @covers Zepto\Router::match() */ public function testMatchFail() { $this->router->get('/notget', function () { return 'This is not a get route'; }); $this->assertNull($this->router->match('/get/', Router::METHOD_GET)); }
public function run() { $route = $this->router->match($this->request); if ($route === false) { $actionName = self::ACTION_NOT_FOUND; } else { $actionName = $route->getName(); } if (!$this->actions->has($actionName)) { throw new \Exception(sprintf('Action %s not found', $actionName)); } $this->store->setFileName($actionName); if ($this->request->isAjax()) { $this->view->setRenderType(View::RENDER_JSON); } else { $this->view->setContentView('error'); } $action = $this->actions->get($actionName); call_user_func_array($action, array($this)); if (is_callable($this->postAction)) { call_user_func_array($this->postAction, array($this)); } $this->response->setContent($this->view->render()); $this->response->send(); }
public function match(Request $request, $route = false) { if ($request->getHostname() == $this->_hostname) { return parent::match($request, new Route()); } return false; }
public function testMatchMethod() { $this->object->add(new \PHPixie\Route('get', '/url', array('controller' => 'home', 'action' => 'get'), 'GeT')); $this->object->add(new \PHPixie\Route('post', '/url', array('controller' => 'home', 'action' => 'get'), array('PosT'))); $route = $this->object->match('/url', 'GEt'); $this->assertEquals('get', $route['route']->name); $route = $this->object->match('/url', 'POST'); $this->assertEquals('post', $route['route']->name); }
/** * Returns the matched route * @return mixed The matched route or false if none matched */ private function match_route() { $match = $this->router->match(); if ($match) { $route = $this->routes[$match['name']]; $route['parameters'] = $match['params']; $this->current_route = $route; return $route; } }
/** * Dispatches a HTTP request to a front controller. * Sends response to output. * * @return void */ public function run() { $request = $this->createRequest(); $applicationRequestInformation = $this->router->match($request); $controllerName = $this->formatControllerName($applicationRequestInformation['controller']); $methodName = $this->formatMethodName($applicationRequestInformation['method']); $templateFileName = $this->formatTemplateFileName($applicationRequestInformation['controller'], $applicationRequestInformation['method']); require_once $this->controllersDir . $controllerName . '.php'; $response = new Response(); $template = new Template($this->templatesDir . $templateFileName); /** @var Controller $controller */ $controller = new $controllerName($template, $response); if (method_exists($controller, $methodName)) { call_user_func_array(array($controller, $methodName), $applicationRequestInformation['parameters']); } $response = $controller->getResponse(); $response->setOutput($controller->getTemplate()->render()); $response->send(); }
public function match(Request $request, $route = false) { if ($request->getUri() == $this->_path) { $static = new Route(); $static->setControllerName($this->_controller); $static->setActionName($this->_action); $static->merge($route); return parent::match($request, $static); } }
public function testAlias() { Router::alias('/', 'home.html'); $result = Router::match('/'); $this->assertTrue($result instanceof Route); $this->assertEquals('home.html', $result->url); $this->assertEquals([], $result->parameters); $this->assertTrue(is_callable($result->callback)); $result = ($result->callback)(new Request()); $this->assertTrue($result instanceof Page); }
public function testChain() { $request = new Request(); $request->setHostname("t.test.local"); $request->setUri("/"); $router = new Router(); $hostnameRouter = new HostnameRouter("t.test.local"); $hostnameRouter->addChild("hello", new StaticRouter("/", "Hello", "world")); $router->addChild("hostname", $hostnameRouter); $route = $router->match($request); $this->assertEquals("Hello", $route->getControllerName()); }
/** * Get and handle HTTP request * * @param void * @return null */ function handleHttpRequest() { $request = $this->router->match(ANGIE_PATH_INFO, ANGIE_QUERY_STRING); if (is_error($request)) { handle_fatal_error($request); } else { $execute =& execute_action($request); if (is_error($execute)) { handle_fatal_error($execute); } // if } // if }
/** * Analyze request, provided $_REQUESt, $_SERVER [, $_GET, $_POST] and identifu Route * * Response type can be set from HTTP_ACCEPT header. the Route object will be set by a call * to Router::match * * @param array $request $_REQUEST * @param array $server $_SERVER * @param array $get $_GET * @param array $post $_POST */ public function __construct(array $request = [], array $server = [], array $get = [], array $post = []) { $this->_request = $request; $this->_server = $server; $this->_post = $post; $this->_get = $get; unset($this->_get['url']); $this->_parameters = []; // override html type with json $httaccept = $this->_server['HTTP_ACCEPT'] ?? '*/*'; if ($httaccept !== '*/*' && strpos($this->_server['HTTP_ACCEPT'], 'application/json') !== false) { $this->_type = 'json'; } $this->_url = $this->_request['url'] ?? '/'; $this->_method = $this->_server['REQUEST_METHOD'] ?? Request::GET; $this->_route = Router::match($this->_url, $this->_method); }
<?php require_once 'init.php'; $router = new Router(); $router->map('GET', '', function () { loadSmarty(); show_page('index', 'Home'); }); $router->map('GET', '/news/:id', function ($id) { return Adapter::invokeAdapter('News', 'obtaionNews', array('id' => $id)); }); $router->map('GET', '/news/', function () { return Adapter::invokeAdapter('News', 'obtaionNews'); }); $router->map('POST', '/news/:id', function ($id) { return Adapter::invokeAdapter('News', 'editNews', array('id' => $id)); }); $router->map('POST', '/news/', function () { return Adapter::invokeAdapter('News', 'addNews'); }); $router->map('DELETE', '/news/:id', function ($id) { return Adapter::invokeAdapter('News', 'deleteNews', array('id' => $id)); }); $router->map('GET', '/users/:userId/', function ($userId) { return Adapter::invokeAdapter('Users', 'getUser', array('userId' => $userId)); }); $router->map('GET', '/users/:userId/comments/[:commentId]', function ($userId, $commentId = 0) { return Adapter::invokeAdapter('Users', 'getUserComments', array('userId' => $userId, 'commentId' => $commentId)); }); echo $router->match();
$router->map('/groups/i:objectGroupID/:scopeObject/:scopeObjectKey/items/top', array('controller' => 'Items', 'extra' => array('subset' => 'top'))); // Items within something else $router->map('/users/i:objectUserID/:scopeObject/:scopeObjectKey/items/:objectKey/:subset', array('controller' => 'Items')); $router->map('/groups/i:objectGroupID/:scopeObject/:scopeObjectKey/items/:objectKey/:subset', array('controller' => 'Items')); // User API keys $router->map('/keys/:objectName', array('controller' => 'Keys')); $router->map('/users/i:objectUserID/keys/:objectName', array('controller' => 'Keys')); // User/library settings $router->map('/users/i:objectUserID/publications/settings/:objectKey', ['controller' => 'settings', 'extra' => ['publications' => true]]); $router->map('/users/i:objectUserID/settings/:objectKey', array('controller' => 'settings')); $router->map('/groups/i:objectGroupID/settings/:objectKey', array('controller' => 'settings')); // Clear (for testing) $router->map('/users/i:objectUserID/clear', array('controller' => 'Api', 'action' => 'clear')); $router->map('/users/i:objectUserID/publications/clear', ['controller' => 'Api', 'action' => 'clear', 'extra' => ['publications' => true]]); $router->map('/groups/i:objectGroupID/clear', array('controller' => 'Api', 'action' => 'clear')); // Other top-level URLs, with an optional key and subset $router->map('/users/i:objectUserID/publications/items/:objectKey/:subset', ['controller' => 'Items', 'extra' => ['publications' => true]]); // Just items for now $router->map('/users/i:objectUserID/publications/deleted', ['controller' => 'Deleted', 'extra' => ['publications' => true]]); $router->map('/users/i:objectUserID/:controller/:objectKey/:subset'); $router->map('/groups/i:objectGroupID/:controller/:objectKey/:subset'); $router->map('/itemTypes', array('controller' => 'Mappings', 'extra' => array('subset' => 'itemTypes'))); $router->map('/itemTypeFields', array('controller' => 'Mappings', 'extra' => array('subset' => 'itemTypeFields'))); $router->map('/itemFields', array('controller' => 'Mappings', 'extra' => array('subset' => 'itemFields'))); $router->map('/itemTypeCreatorTypes', array('controller' => 'Mappings', 'extra' => array('subset' => 'itemTypeCreatorTypes'))); $router->map('/creatorFields', array('controller' => 'Mappings', 'extra' => array('subset' => 'creatorFields'))); $router->map('/items/new', array('controller' => 'Mappings', 'action' => 'newItem')); $router->map('/test/setup', array('controller' => 'Api', 'action' => 'testSetup')); } return $router->match($_SERVER['REQUEST_URI']);
public function testNoPagesDir() { $router = new Router(); $this->setExpectedException('RuntimeException'); $router->match('/hello.php'); }
$folderMapper = new FolderMapper($db); //__construct($folderId, $name, $folderInId, $userId) $folder = new Folder($query["folderId"], $query["name"], $query["folderParentId"], $query["userId"]); $folderMapper->update($folder); die("Folder Renamed Successfully!"); } else { die("Input all params!"); } }); $rout_r->map('GET', '/api/folder/delete/', function () { session_start(); global $GLOBALS; $query = $GLOBALS['query']; if (isset($query["folderId"]) || isset($query["name"]) || isset($query["folderParentId"]) || isset($query["userId"])) { $db = new MySqlDAO(); $folderMapper = new FolderMapper($db); $folderMapper->delete($query["folderId"]); die("Folder Deleted Successfully!"); } else { die("Input all params!"); } }); $rout_r->map('GET', '/api/user/logout/', function () { session_start(); if (isset($_SESSION['userID'])) { unset($_SESSION['userID']); (new ReportingFramework())->report(['condition' => "success", 'message' => '']); } }); $rout_r->match();
-------------------------------------------------------------------------------- */ foreach (glob(ELSA . '/app/modules/*.php') as $module) { require $module; } /* -------------------------------------------------------------------------------- Autoload app controllers -------------------------------------------------------------------------------- */ foreach (glob(ELSA . '/app/controllers/*.php') as $controller) { require $controller; } /* -------------------------------------------------------------------------------- Init -------------------------------------------------------------------------------- */ session_start(); $route = new Router(); /* -------------------------------------------------------------------------------- Go forth! -------------------------------------------------------------------------------- */ require ELSA . '/app/before.php'; require ELSA . '/system/routes.php'; require ELSA . '/app/routes.php'; require ELSA . '/app/after.php'; $route->dispatchController($route->match());
if (!$route instanceof Container) { continue; } $path = $route->getPath(); if (strlen($path) && $path == $uri) { Router::make($route); return true; } if (!strlen($path) && !strlen($uri)) { if (null !== $route->getRedirect()) { Router::redirect('/' . $route->getRedirect()); } Router::make($route); return true; } $matched = Router::match($path, $route, $uri); if (false === $matched || !count($matched)) { continue; } else { if (null !== $route->getRedirect()) { Router::redirect('/' . $route->getRedirect()); } Router::make($route); return true; } } } }); context()->isPost(function ($except = array()) { if (count($_POST) && count($except)) { foreach ($except as $key) {
Response::error(401, $_SERVER["SERVER_PROTOCOL"] . ' 401 Unauthorized (USER is missing required access rights). '); } if (!$feide->hasAdminScope()) { Response::error(401, $_SERVER["SERVER_PROTOCOL"] . ' 401 Unauthorized (CLIENT is missing required scope). '); } } /** * http://stackoverflow.com/questions/4861053/php-sanitize-values-of-a-array/4861211#4861211 */ function sanitizeInput() { $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING); $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING); } // -------------------- ./UTILS -------------------- // // ---------------------- MATCH AND EXECUTE REQUESTED ROUTE ---------------------- $match = $router->match(); if ($match && is_callable($match['target'])) { verifyOrgAccess(); sanitizeInput(); call_user_func_array($match['target'], $match['params']); } else { Response::error(404, $_SERVER["SERVER_PROTOCOL"] . " The requested resource [" . get_path_info() . "] could not be found."); } // ---------------------- /.MATCH AND EXECUTE REQUESTED ROUTE ---------------------- function get_path_info() { global $API_BASE_PATH; $requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; return substr($requestUrl, strlen($API_BASE_PATH)); }
<?php //spl_autoload_register(); require '../Core/Router.php'; $router = new Router(); $router->add('', ['controller' => 'Home', 'action' => 'index']); $router->add('posts', ['controller' => 'Posts', 'action' => 'index']); //$router->add('posts/new', ['controller' => 'Posts', 'action' => 'new']); $router->add('{controller}/{action}'); $router->add('admin/{controller}/{action}'); $url = $_SERVER['QUERY_STRING']; if ($router->match($url)) { echo '<pre>'; var_dump($router->getRoutes()); var_dump($router->getParams()); echo '</pre>'; } else { echo 'no routes found for URL ' . $url; }
require_once CONTROLLER_DIR . '/LoginController.php'; require_once CONTROLLER_DIR . '/RoutingController.php'; require_once CONTROLLER_DIR . '/DatabaseController.php'; require_once MODEL_DIR . '/ImageModel.php'; require_once MODEL_DIR . '/UserModel.php'; session_start(); $connection = new PDO('mysql:host=127.0.0.1;dbname=imagegallery;charset=utf8mb4', 'root', 'emil0609'); $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $container = new Container(); $container->bindArguments('RoutingController', ['connection' => $connection, 'container' => $container]); $container->bindArguments('ImageModel', ['connection' => $connection]); $container->bindArguments('UserModel', ['connection' => $connection]); $router = new Router(); $router->addRoute('GET', '/', ['RoutingController', 'renderLoginView']); $router->addRoute('POST', '/login', ['LoginController', 'login']); $router->addRoute('GET', '/gallery', ['RoutingController', 'renderGalleryView']); $router->addRoute('GET', '/logout', ['LoginController', 'logout']); $router->addRoute('GET', '/upload', ['RoutingController', 'renderUploadView']); $router->addRoute('GET', '/users', ['RoutingController', 'renderUsersView']); $router->addRoute('GET', '/create', ['RoutingController', 'test']); $router->addRoute('GET', '/delete', ['UserModel', 'deleteUser']); $router->addRoute('GET', '/getusers', ['UserModel', 'getUsers']); $router->addRoute('POST', '/createimage', ['ImageModel', 'createImage']); $router->addRoute('GET', '/getimages', ['ImageModel', 'getImages']); $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); $route = $router->match($_SERVER['REQUEST_METHOD'], $uri); if ($route == null) { $route = ['handle' => ['ErrorController', 'error404'], 'arguments' => []]; } $controller = $container->create($route['handle'][0]); $container->call([$controller, $route['handle'][1]], $route['arguments']);
private function getRequestedMethodValidity($requestedMethod, $routeRuleMethod, $expected) { $_SERVER['REQUEST_METHOD'] = $requestedMethod; $_SERVER['REQUEST_URI'] = PATH . '/tests.php/news/'; $router = new Router(true); $router->map($routeRuleMethod, '/news/', function () { return Adapter::invokeAdapter('News', 'addNews'); }); $actual = json_decode($router->match(), true); $testStatus = $this->getStatus($expected, $actual); return $testStatus; }
private function route($url) { if (!file_exists(APP . 'config' . DS . 'routes.php')) { return $url; } require_once LIB . 'kata' . DS . 'router.php'; include APP . 'config' . DS . 'routes.php'; $router = new Router(); $match = $router->match($url); if (!$match) { return $url; } return $match['target'] . '/' . implode('/', $match['params']); }
public function testNoMatch() { $router = new Router([]); $this->assertEquals([], $router->match("/")); $this->assertEquals("", $router->invoke("/")); }