Removed named arguments from call_user_func

This commit is contained in:
tracer 2022-10-22 19:51:20 +02:00
parent a55b14c71c
commit f571d7548a
1 changed files with 9 additions and 2 deletions

View File

@ -11,7 +11,7 @@ class Router
private array $routes; private array $routes;
/* /*
* This method takes a route like /admin/users/{user} and create a regex to match on call * This method takes a route like /admin/users/{user} and creates a regex to match on call
*/ */
function addRoute(string $name, string $route, Closure $callback): void function addRoute(string $name, string $route, Closure $callback): void
{ {
@ -21,8 +21,10 @@ class Router
// create regex for route: // create regex for route:
$regex = preg_replace(pattern: '/(?<={).+?(?=})/', replacement: '(.*?)', subject: $route); $regex = preg_replace(pattern: '/(?<={).+?(?=})/', replacement: '(.*?)', subject: $route);
// code below is ugly, better match including the braces
$regex = str_replace(search: '{', replace: '', subject: $regex); $regex = str_replace(search: '{', replace: '', subject: $regex);
$regex = str_replace(search: '}', replace: '', subject: $regex); $regex = str_replace(search: '}', replace: '', subject: $regex);
$regex = '/^' . str_replace(search: "/", replace: '\\/', subject: $regex) . '$/i'; $regex = '/^' . str_replace(search: "/", replace: '\\/', subject: $regex) . '$/i';
$route = new Route(name: $name, route: $route, regEx: $regex, parameters: $parameters, callback: $callback); $route = new Route(name: $name, route: $route, regEx: $regex, parameters: $parameters, callback: $callback);
@ -39,8 +41,13 @@ class Router
foreach ($route->getParameters() as $id => $parameter) { foreach ($route->getParameters() as $id => $parameter) {
$parameters[$parameter] = $matches[$id +1]; $parameters[$parameter] = $matches[$id +1];
} }
call_user_func(callback: $route->getCallback(), args: $parameters); // PHP is mad about named parameters in call_user_func
// Uncaught Error: Unknown named parameter $args in …
// But PHPStorm seems happy without them. So what?
call_user_func($route->getCallback(), $parameters);
return;
} }
} }
die("Invalid route: $requestUri");
} }
} }