/** * @param RequestInterface $request A request. * @return ResolvedRequestInterface * @throws OutOfRangeException * @throws Exception */ public function route(RequestInterface $request) { if (!is_null($this->cachePath)) { $dispatcher = \FastRoute\cachedDispatcher(function (RouteCollector $collector) { foreach ($this->routes as $route) { $collector->addRoute($route->getRequestType(), $route->getUri(), serialize($route)); } }, ['cacheFile' => $this->cachePath]); } else { // Add routes to the route collector. $dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $collector) { foreach ($this->routes as $route) { $collector->addRoute($route->getRequestType(), $route->getUri(), serialize($route)); } }); } // Dispatch the route. $route_info = $dispatcher->dispatch($request->getMethod(), $request->getUriPath()); // Handle the route depending on the response type. switch ($route_info[0]) { // Route not found. case Dispatcher::NOT_FOUND: throw new OutOfRangeException("No route matched the given URI."); // Method not allowed for the specified route. // Method not allowed for the specified route. case Dispatcher::METHOD_NOT_ALLOWED: throw new Exception("Method not allowed."); // Route found. // Route found. case Dispatcher::FOUND: $route = $route_info[1]; $params = $route_info[2]; return new ResolvedRequest($request, unserialize($route), $params); } }
function routeRequest(Response $response, Request $request) { $routesDefinitionsCallback = function (RouteCollector $r) { foreach (require __DIR__ . "/routes.php" as $route) { $r->addRoute($route[0], $route[1], $route[2]); } }; $dispatcher = \FastRoute\simpleDispatcher($routesDefinitionsCallback); $routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getPath()); switch ($routeInfo[0]) { case Dispatcher::NOT_FOUND: $response->setStatusCode(404); $response->setContent('404 - not found'); break; case Dispatcher::METHOD_NOT_ALLOWED: $response->setStatusCode(403); $response->setContent('403 - not allowed'); break; case Dispatcher::FOUND: $response->setStatusCode(200); $className = $routeInfo[1][0]; $method = $routeInfo[1][1]; $vars = $routeInfo[2]; return new Step("{$className}::{$method}", InjectionParams::fromRouteParams($vars)); } return new step(function () { echo "something went wrong"; }); }
public function __invoke(Go $message) { $actions = $this->actions; $dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) use($actions) { foreach ($actions as $action) { if ($action->getMatcher() instanceof Route == false) { continue; } $route = $action->getMatcher(); $r->addRoute($route->method, $route->uriTemplate, function ($variables = []) use($action) { // TODO: Extract (post) variables from request and insert into action some way easy to consume // URI Variables = parameter // Get Variables = parameter // POST Variables = entity object added to parameters $action->handle($variables); }); } }); $uri = (string) $this->request->getUri()->getPath(); $method = $this->request->getMethod(); $routeInfo = $dispatcher->dispatch($method, $uri); switch ($routeInfo[0]) { case \FastRoute\Dispatcher::NOT_FOUND: // TODO: Use a more specialized exception throw new \Exception('No action could be found to deal with uri "' . $uri . '" and method "' . $method . '"'); case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: $allowedMethods = $routeInfo[1]; // TODO: Use a more specialized exception throw new \Exception('The method "' . $method . '" is not allowed with uri "' . $uri . '". The following are allowed ' . 'methods: ' . implode($allowedMethods)); case \FastRoute\Dispatcher::FOUND: list(, $handler, $vars) = $routeInfo; $handler($vars); break; } }
public function __construct($config) { $this->config = $config; //var_dump($this->config); $this->dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) { foreach ($this->config['auths'] as $id => $route) { log::prn_log(DEBUG, 'addRoute: ' . json_encode($route)); $r->addRoute($route[0], $route[1], 'func_' . $id); $this->config['auths'][$id]['users'] = []; $users = explode(',', $route[2]); foreach ($users as $user) { if (substr($user, 0, 1) != '@') { if (!in_array($user, $this->config['auths'][$id]['users'])) { $this->config['auths'][$id]['users'][] = $user; } } else { $users2 = explode(',', $this->config['groups'][substr($user, 1)]); foreach ($users2 as $user) { if (!in_array($user, $this->config['auths'][$id]['users'])) { $this->config['auths'][$id]['users'][] = $user; } } } } if (in_array('*', $this->config['auths'][$id]['users'])) { unset($this->config['auths'][$id]['users']); $this->config['auths'][$id]['users'][0] = '*'; } } }); }
/** * @param $httpMethod * @param $uri * @return null|\stdClass */ public function dispatch($httpMethod, $uri) { if (false !== ($pos = strpos($uri, '?'))) { $uri = substr($uri, 0, $pos); } $uri = rawurldecode($uri); $routes = $this->getRoutes(); /** * @var \FastRoute\Dispatcher $dispatcher */ $dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $r) use($routes) { foreach ($routes as $route) { $r->addRoute($route[0], $route[1], $route[2]); } }); $routeInfo = $dispatcher->dispatch($httpMethod, $uri); if ($routeInfo[0] == \FastRoute\Dispatcher::FOUND) { $routeParams = $routeInfo[2]; if (is_array($routeParams) == false) { $routeParams = array(); } $this->currentRoute = new \stdClass(); $this->currentRoute->handler = $routeInfo[1]; $this->currentRoute->params = $routeParams; return $this->currentRoute; } else { return null; } }
/** * Dispatches request to a controller * * @param IContainer $container * @return mixed */ public function dispatch(IContainer $container) { $dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $r) { foreach ($this->config as $config) { $r->addRoute($config[0], $config[1], $config[2]); } }); $httpMethod = $_SERVER['REQUEST_METHOD']; $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $routeInfo = $dispatcher->dispatch($httpMethod, $uri); switch ($routeInfo[0]) { case RouteDispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; $controller = $handler; $method = 'index'; if (strpos($handler, '@') !== false) { list($controller, $method) = explode('@', $handler); } $controller = $container->make($controller); $controller->{$method}(...array_values($vars)); break; case RouteDispatcher::NOT_FOUND: $controller = $container->make('RomanNumerals\\Controller'); $controller->response(['error' => 'Command not found'], 404); break; case RouteDispatcher::METHOD_NOT_ALLOWED: $allowedMethods = $routeInfo[1]; $controller = $container->make('RomanNumerals\\Controller'); $controller->response(['error' => 'Method is not allowed, allowed methods are: ' . implode(', ', $allowedMethods)], 405); break; } }
function getRouteCallable() { $dispatcher = FastRoute\simpleDispatcher('routesFunction'); $httpMethod = 'GET'; //yay hard coding. $uri = '/'; if (array_key_exists('REQUEST_URI', $_SERVER)) { $uri = $_SERVER['REQUEST_URI']; } $path = $uri; $queryPosition = strpos($path, '?'); if ($queryPosition !== false) { $path = substr($path, 0, $queryPosition); } $routeInfo = $dispatcher->dispatch($httpMethod, $path); switch ($routeInfo[0]) { case FastRoute\Dispatcher::NOT_FOUND: return new StandardHTTPResponse(404, $uri, "Not found"); case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: $allowedMethods = $routeInfo[1]; // ... 405 Method Not Allowed return new StandardHTTPResponse(405, $uri, "Not allowed"); case FastRoute\Dispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; $params = InjectionParams::fromParams($vars); return new Tier($handler, $params); default: //Not supported return new StandardHTTPResponse(404, $uri, "Not found"); break; } }
function nikic_fast_route() { $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) { $r->addRoute(['GET', 'POST'], '/test', 'action_test'); $r->addRoute(['GET', 'POST'], '/test/{id:\\d+}', 'action_handler_numeric'); $r->addRoute(['GET', 'POST'], '/test/{key:\\w+}', 'action_handler'); }); $httpMethod = $_SERVER['REQUEST_METHOD']; $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); $routeInfo = $dispatcher->dispatch($httpMethod, $uri); switch ($routeInfo[0]) { case FastRoute\Dispatcher::NOT_FOUND: MyDefaultControllerClass::indexMethod(null, null); break; case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: $allowedMethods = $routeInfo[1]; // ... 405 Method Not Allowed echo 'not allowed'; break; case FastRoute\Dispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; // ... call $handler with $vars $handler($uri, $vars); break; } }
public function container() { $this->c = new Container(); $this->c['controller'] = new Controller(); $this->c['dispatcher'] = function ($c) { return \FastRoute\simpleDispatcher($c['handlers']); }; }
/** * @param RouteCollection $collection * * @return Dispatcher */ private function createDispatcher(RouteCollection $collection) { return \FastRoute\simpleDispatcher(function (RouteCollector $collector) use($collection) { foreach ($collection as $route) { $collector->addRoute($route->methods(), $route->uri(), $route); } }); }
protected function createDispatcher() { return \FastRoute\simpleDispatcher(function ($r) { foreach ($this->routes as $route) { $r->addRoute($route['method'], $route['uri'], $route['action']); } }); }
public function __construct($routes) { $this->collection = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) use($routes) { foreach ($routes as $identifier => $routeData) { $r->addRoute($routeData[0], $routeData[1], $identifier); } }, ['cacheFile' => __DIR__ . '/route.cache']); }
/** * @param array $routes */ public function __construct($routes) { $this->routes = $routes; $this->dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) use($routes) { foreach ($routes as $route => $provider) { $r->addRoute(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'], $route, $provider); } }); }
/** * @return Dispatcher */ protected function getDispatcher() { return \FastRoute\simpleDispatcher(function (RouteCollector $collector) { foreach ($this->router->getRoutes() as $name => $route) { list($method, $path) = explode(' ', $name, 2); $collector->addRoute($method, $path, $route); } }); }
/** * Sets up the dispatcher * * @return [type] [description] */ private function setupDispatcher() { $callback = function (\FastRoute\RouteCollector $r) { foreach ($this->routes as $route) { $r->addRoute($route[0], $route[1], $route[2]); } }; $this->dispatcher = \FastRoute\simpleDispatcher($callback); }
public function setUp() { $router = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) { $r->addRoute('GET', '/', [get_class($this), 'index']); }); $this->app = new App($router); $dispatcher = new FastSymfonyDispatcher($router); $this->app->getContainer()->set("dispatcher", $dispatcher); }
public function __construct() { $this->dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $route) { include 'routers.php'; }); // Fetch method and URI from somewhere $httpMethod = $_SERVER['REQUEST_METHOD']; $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); $this->routeInfo = $this->dispatcher->dispatch($httpMethod, $uri); }
/** * @return Dispatcher */ protected function dispatchRoutes() : Dispatcher { /** @var $dispatcher */ return \FastRoute\simpleDispatcher(function (RouteCollector $route) { $collections = $this->collection->getCollection(); foreach ($collections as $collect) { list($method, $uri, $action) = $collect; $route->addRoute($method, $uri, $action); } }); }
/** * Configure the dispatcher. * * @param array $routes */ private function configureDispatcher(array $routes) { $this->dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $routeCollector) use(&$routes) { foreach ($routes as $route) { $method = $route[0]; $uri = $route[1]; $callback = array($route[2], $route[3]); $routeCollector->addRoute($method, $uri, $callback); } }); }
public function __construct($config) { $this->config_route = array_merge($config, Route_config::$default_route); //var_dump($this->config_route); $this->dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) { foreach ($this->config_route as $route) { log::prn_log(DEBUG, 'addRoute: ' . json_encode($route)); $r->addRoute($route[0], $route[1], [$this, $route[2]]); } }); }
/** * 执行http操作,解析路由执行控制器 * @param HttpRequest $request * @return mixed * @throws RouteException * @throws \Exception */ public function handleAction(HttpRequest $request) { $route = \FastRoute\simpleDispatcher(function (RouteCollector $route) { $route->addRoute('*', '/', $this->defaultRoute); $route->addRoute('*', '{controller:(?![/?]{2,})[a-zA-Z/]{1,}}/{action:[a-zA-Z]{1}[a-zA-Z0-9]{0,}}', ''); }); $result = $route->dispatch($request->getMethod(), $request->getBaseURI()); if (!array_shift($result)) { throw new RouteException('invalid url'); } $this->resolveAction($result, $request); return $this->runController($request); }
public function testFastRoute() { $dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) { $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', function ($request, $response) { $response->getBody()->write(json_encode(['name' => $request->getAttribute('name'), 'id' => $request->getAttribute('id')])); return $response; }); }); $response = $this->execute([Middleware::FastRoute($dispatcher)], 'http://domain.com/user/oscarotero/35'); $body = json_decode((string) $response->getBody(), true); $this->assertEquals($body['name'], 'oscarotero'); $this->assertEquals($body['id'], '35'); }
/** * Sets up FastRoute tests */ function setupFastRoute(Benchmark $benchmark, $routes, $args) { $argString = implode('/', array_map(function ($i) { return "{arg{$i}}"; }, range(1, $args))); $str = $firstStr = $lastStr = ''; $router = \FastRoute\simpleDispatcher(function ($router) use($routes, $argString, &$lastStr, &$firstStr) { for ($i = 0; $i < $routes; $i++) { list($pre, $post) = getRandomParts(); $str = '/' . $pre . '/' . $argString . '/' . $post; if (0 === $i) { $firstStr = str_replace(array('{', '}'), '', $str); } $lastStr = str_replace(array('{', '}'), '', $str); $router->addRoute('GET', $str, 'handler' . $i); } }); $benchmark->register(sprintf('FastRoute - first route', $routes), function () use($router, $firstStr) { $route = $router->dispatch('GET', $firstStr); }); }
/** * Initialize the route handler. * * @throws \ErrorException */ public function initRoute() { $routes = (require $this->routesPath); $dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $collector) use($routes) { foreach ($routes as $route) { $collector->addRoute($route[0], $route[1], $route[2]); } }); $method = filter_input(INPUT_SERVER, 'REQUEST_METHOD'); $uri = rawurldecode(parse_url(filter_input(INPUT_SERVER, 'REQUEST_URI'), PHP_URL_PATH)); $route = $dispatcher->dispatch($method, $uri); switch ($route[0]) { case \FastRoute\Dispatcher::NOT_FOUND: throw new \ErrorException("Route {$method} {$uri} not found."); break; case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: throw new \ErrorException("Method {$method} not allowed."); break; case \FastRoute\Dispatcher::FOUND: $handler = $route[1]; $arguments = $route[2]; call_user_func_array($handler, $arguments); } }
$whoops = new \Whoops\Run(); if ($environment !== 'production') { $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler()); } else { $whoops->pushHandler(function ($e) { echo 'Friendly error page and send an email to the developer'; }); } $whoops->register(); $routeDefinitionCallback = function (\FastRoute\RouteCollector $r) { $routes = (include 'Routes.php'); foreach ($routes as $route) { $r->addRoute($route[0], $route[1], $route[2]); } }; $dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback); $routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo()); switch ($routeInfo[0]) { case \FastRoute\Dispatcher::NOT_FOUND: $response->setContent('404 - Page not found'); $response->setStatusCode(404); break; case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: $response->setContent('405 - Method not allowed'); $response->setStatusCode(405); break; case \FastRoute\Dispatcher::FOUND: $className = $routeInfo[1][0]; $method = $routeInfo[1][1]; $vars = $routeInfo[2]; $class = $injector->make($className);
$response = $injector->make('Symfony\\Component\\HttpFoundation\\Response'); $renderer = $injector->make('Pics\\Template\\Renderer'); $pdo = $injector->make('PDO'); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $m = $injector->make('Memcached'); $m->addServer('127.0.0.1', 11211); // Error handler if ($config['environment'] !== 'production') { $whoops = new \Whoops\Run(); $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler()); $whoops->register(); } // Routing $dispatcher = \FastRoute\simpleDispatcher(function (\FastRoute\RouteCollector $r) { $routes = (include 'Routes.php'); foreach ($routes as $route) { $r->addRoute($route[0], $route[1], $route[2]); } }); $routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo()); switch ($routeInfo[0]) { case \FastRoute\Dispatcher::NOT_FOUND: if (!$request->isXmlHttpRequest()) { $html = $renderer->render('Error', array('code' => 404, 'message' => 'Page not found :(')); } $response->setContent($html); $response->setStatusCode(Response::HTTP_NOT_FOUND); $response->send(); break; case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: if (!$request->isXmlHttpRequest()) { $html = $renderer->render('Error', array('code' => 405, 'message' => 'Method not allowed'));
* @author shsrain <*****@*****.**> */ // 定义入口根目录。 defined('BASE_PATH') or define('BASE_PATH', str_replace('\\', '/', realpath(dirname(__FILE__) . '/')) . "/"); // 加载核心文件。 require_once __DIR__ . '/app.php'; $app = app(); $httpKernel = function ($request, $response) use($app) { // 注册消息。 $app['request'] = $request; $app['response'] = $response; // 创建消息路由。 $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) use($app) { $app['router'] = $r; $app['path_block'] = array_values(array_filter(explode('/', $app['request']->getPath()))); if (!empty($app['path_block'])) { $app['loader']->manifest($app['path_block'][0], $app); } }); // 消息解析来源。 $httpMethod = $app['request']->getMethod(); $uri = parse_url($app['request']->getPath(), PHP_URL_PATH); $routeInfo = $dispatcher->dispatch($httpMethod, $uri); // 路由解析。 switch ($routeInfo[0]) { case FastRoute\Dispatcher::NOT_FOUND: // ... 404 Not Found $headers = array('Content-Type' => 'text/plain'); $app['response']->writeHead(404, $headers); $app['response']->end('404'); break;
$whoops->pushHandler(function () { Response::create('Something broke', Response::HTTP_INTERNAL_SERVER_ERROR)->send(); }); } $whoops->register(); /** * Container setup */ $container = new Container(); $container->add('PDO')->withArgument(getenv('DB_CONN'))->withArgument(getenv('DB_USER'))->withArgument(getenv('DB_PASS')); /** * Routes */ $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) { $routes = (require __DIR__ . '/routes.php'); foreach ($routes as $route) { $r->addRoute($route[0], $route[1], $route[2]); } }); /** * Dispatch */ $request = Request::createFromGlobals(); $route_info = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo()); switch ($route_info[0]) { case Dispatcher::NOT_FOUND: Response::create("404 Not Found", Response::HTTP_NOT_FOUND)->send(); break; case Dispatcher::METHOD_NOT_ALLOWED: Response::create("405 Method Not Allowed", Response::HTTP_METHOD_NOT_ALLOWED)->send(); break; case Dispatcher::FOUND:
<?php require "vendor/autoload.php"; use Icicle\Http\Message\RequestInterface; use Icicle\Http\Server\Server; use Icicle\Loop; use Icicle\Socket\SocketInterface; $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $collector) { require __DIR__ . "/routes.php"; }); $server = new Server(function (RequestInterface $request, SocketInterface $socket) use($dispatcher) { $dispatched = $dispatcher->dispatch($request->getMethod(), $request->getRequestTarget()); switch ($dispatched[0]) { case FastRoute\Dispatcher::NOT_FOUND: // there is no matching route break; case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: // the method called on this route is invalid break; case FastRoute\Dispatcher::FOUND: (yield call_user_func($dispatched[1], $request, $socket, $dispatched[2])); break; } }); $server->listen(8000); Loop\run();
define('ROOT', realpath(__DIR__ . '/..')); session_start(); require __DIR__ . '/../vendor/autoload.php'; use FastRoute\Dispatcher; use FastRoute\RouteCollector; use Psr\Log\LoggerInterface; use SitePoint\Rauth; use Tamtamchik\SimpleFlash\Flash; use DI\ContainerBuilder; $containerBuilder = new ContainerBuilder(); $container = $containerBuilder->addDefinitions(require_once __DIR__ . '/../app/config/config_web.php')->useAnnotations(true)->build(); $routeList = (require __DIR__ . '/../app/routes.php'); /** @var Dispatcher $dispatcher */ $dispatcher = FastRoute\simpleDispatcher(function (RouteCollector $r) use($routeList) { foreach ($routeList as $routeDef) { $r->addRoute($routeDef[0], $routeDef[1], $routeDef[2]); } }); $route = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']); switch ($route[0]) { case FastRoute\Dispatcher::NOT_FOUND: echo $container->get(Twig_Environment::class)->render('error404.twig'); break; case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: echo $container->get(Twig_Environment::class)->render('error405.twig'); break; case FastRoute\Dispatcher::FOUND: $controller = $route[1]; $parameters = $route[2]; /** @var Rauth $rauth */ $rauth = $container->get('rauth');