dir commit
This commit is contained in:
src
53
src/Service/Router.php
Normal file
53
src/Service/Router.php
Normal file
@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
|
||||
class Router
|
||||
{
|
||||
private array $uri;
|
||||
private array $routes;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$uri = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH);
|
||||
$this->uri = explode(separator: '/', string: $uri);
|
||||
}
|
||||
|
||||
public function registerRoute(string $route, \Closure $callback): void
|
||||
{
|
||||
$this->routes[$route] = $callback;
|
||||
}
|
||||
|
||||
|
||||
private function matchRoute($url = '/users/tracer/posts/tracer', $method = 'GET')
|
||||
{
|
||||
$reqUrl = $url;
|
||||
|
||||
$reqUrl = rtrim(string: $reqUrl, characters: "/");
|
||||
|
||||
foreach ($this->routes as $route => $closure) {
|
||||
// convert urls like '/users/:uid/posts/:pid' to regular expression
|
||||
// $pattern = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['url'])) . "$@D";
|
||||
$pattern = "@^" . preg_replace('\\/users/:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', $route) . "$@D";
|
||||
// echo $pattern."\n";
|
||||
$params = [];
|
||||
// check if the current request params the expression
|
||||
$match = preg_match($pattern, $reqUrl, $params);
|
||||
if ($match) {
|
||||
// remove the first match
|
||||
array_shift($params);
|
||||
// call the callback with the matched positions as params
|
||||
// return call_user_func_array($route['callback'], $params);
|
||||
return [$route, $params];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
public function handleRouting(): void
|
||||
{
|
||||
$foo = $this->matchRoute();
|
||||
var_dump($foo);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user