Joywork/constructor/api/Routes/Router.php

34 lines
1.3 KiB
PHP
Raw Permalink Normal View History

2026-05-22 20:21:54 +02:00
<?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');
}
}