You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
flight-core/flight/net/Router.php

120 lines
2.6 KiB

14 years ago
<?php
declare(strict_types=1);
14 years ago
/**
* Flight: An extensible micro-framework.
14 years ago
*
* @copyright Copyright (c) 2011, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
14 years ago
*/
namespace flight\net;
/**
* The Router class is responsible for routing an HTTP request to
* an assigned callback function. The Router tries to match the
* requested URL against a series of URL patterns.
*/
class Router
{
14 years ago
/**
* Case sensitive matching.
14 years ago
*/
public bool $case_sensitive = false;
/**
* Mapped routes.
* @var array<int, Route>
*/
protected array $routes = [];
/**
* Pointer to current route.
*/
protected int $index = 0;
/**
* Gets mapped routes.
*
* @return array<int, Route> Array of routes
*/
public function getRoutes(): array
{
return $this->routes;
}
/**
* Clears all routes in the router.
*/
public function clear(): void
{
$this->routes = [];
}
14 years ago
/**
* Maps a URL pattern to a callback function.
*
* @param string $pattern URL pattern to match
* @param callable $callback Callback function
* @param bool $pass_route Pass the matching route object to the callback
14 years ago
*/
public function map(string $pattern, callable $callback, bool $pass_route = false): void
{
4 years ago
$url = trim($pattern);
$methods = ['*'];
4 years ago
if (false !== strpos($url, ' ')) {
[$method, $url] = explode(' ', $url, 2);
$url = trim($url);
$methods = explode('|', $method);
14 years ago
}
11 years ago
$this->routes[] = new Route($url, $callback, $methods, $pass_route);
14 years ago
}
/**
* Routes the current request.
14 years ago
*
* @param Request $request Request object
*
* @return bool|Route Matching route or false if no match
14 years ago
*/
public function route(Request $request)
{
$url_decoded = urldecode($request->url);
while ($route = $this->current()) {
if ($route->matchMethod($request->method) && $route->matchUrl($url_decoded, $this->case_sensitive)) {
return $route;
14 years ago
}
$this->next();
14 years ago
}
return false;
}
/**
* Gets the current route.
14 years ago
*
* @return bool|Route
14 years ago
*/
public function current()
{
return $this->routes[$this->index] ?? false;
}
14 years ago
/**
* Gets the next route.
*/
public function next(): void
{
$this->index++;
}
14 years ago
/**
* Reset to the first route.
*/
public function reset(): void
{
$this->index = 0;
14 years ago
}
}