3v4l.org

run code in 500+ PHP versions simultaneously
<?php class RouteCollector { private array $routes; /* [path => [httpMethod => callback]] [ '/' => [ ['GET' => fn()], ['POST' => fn()] ] ] */ public function add(string $httpMethod, string $path, string|callable $callback): void { $this->routes[$path][$httpMethod] = $callback; } public function getRoutes(): array { return $this->routes; } } class RouteDispatcher { private string | \Closure $callback; # 404 Not Found public private(set) bool $isRouteFound = false; # 405 Method Not Allowed public private(set) bool $isMethodAllowed = false; public private(set) array $allowedMethods = []; public function __construct( private array $routes ){ } public function dispatch(string $httpMethod, string $uri): void { $result = $this->match($uri); # Found route verification if (!$result) { return; } $this->isRouteFound = true; # Method verification if (array_key_exists($httpMethod, $this->routes[$result])) { $this->isMethodAllowed = true; $this->callback = $this->routes[$result][$httpMethod]; } else { $this->allowedMethods = array_keys($this->routes[$result]); } } public function match(string $uri): ?string { $match = array_filter( $this->routes, fn($path): bool => $path === $uri, ARRAY_FILTER_USE_KEY ); return key($match); } public function getCallback(): string | \Closure { return $this->callback; } } /****************************************************************/ $router = new RouteCollector(); $router->add('GET', '/user/login', fn() => 'Form!'); $router->add('POST', '/user/login', fn() => 'Processing!'); $router->add('GET', '/hello', function () { return 'Hello ' . htmlspecialchars($_GET['user'] ?? '') .'!'; }); $router->add('POST', '/admin', fn() => 'Hello Admin!'); # 405 route $router->add('GET', '/', fn() => 'Hello World!'); $dispatcher = new RouteDispatcher($router->getRoutes()); $dispatcher->dispatch( 'PUT', '/user/login' ); echo match (true) { ! $dispatcher->isRouteFound => '404 Sorry, nothing here.', ! $dispatcher->isMethodAllowed => '405 Allowed is: ' . implode(', ', $dispatcher->allowedMethods), default => $dispatcher->getCallback()() };
Output for 8.4.9 - 8.4.24, 8.5.5 - 8.5.9
405 Allowed is: GET, POST
Output for 8.2.31 - 8.2.32, 8.3.5 - 8.3.32
Fatal error: Multiple access type modifiers are not allowed in /in/dZNFB on line 33
Process exited with code 255.

preferences:
49.42 ms | 541 KiB | 4 Q