34 lines
1.3 KiB
PHP
34 lines
1.3 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
class Router {
|
||
|
|
private $base_url = '/constructor/api';
|
||
|
|
protected $routes = []; // stores routes
|
||
|
|
|
||
|
|
public function addRoute($method, $url, $target) {
|
||
|
|
$path = $this->base_url . $url;
|
||
|
|
$this->routes[$method][$path] = $target;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function matchRoute() {
|
||
|
|
$method = $_SERVER['REQUEST_METHOD'];
|
||
|
|
$url = $_SERVER['REQUEST_URI'];
|
||
|
|
$parsedUrl = parse_url($url);
|
||
|
|
if (isset($this->routes[$method])) {
|
||
|
|
foreach ($this->routes[$method] as $routeUrl => $target) {
|
||
|
|
// Simple string comparison to see if the route URL matches the requested URL
|
||
|
|
// var_dump($routeUrl, $url);
|
||
|
|
// var_dump($parsedUrl['path'], $routeUrl);die;
|
||
|
|
$pattern = preg_replace('/\/:([^\/]+)/', '/(?P<$1>[^/]+)', $routeUrl);
|
||
|
|
if (preg_match('#^' . $pattern . '$#', $parsedUrl['path'], $matches)) {
|
||
|
|
// Pass the captured parameter values as named arguments to the target function
|
||
|
|
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY); // Only keep named subpattern matches
|
||
|
|
// if ($routeUrl === $parsedUrl['path']) {
|
||
|
|
list($class, $function) = $target;
|
||
|
|
$class = __NAMESPACE__ . '\\' . $class;
|
||
|
|
call_user_func([new $class, $function], $params);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
throw new Exception('Route not found');
|
||
|
|
}
|
||
|
|
}
|