|
- <?php
-
- declare(strict_types=1);
-
- namespace Core;
-
- class Route
- {
- protected string $method;
- protected string $path;
- protected mixed $handler;
- protected array $parameters = [];
- protected string $compiledPattern;
- protected array $parameterNames = [];
-
- public function __construct(string $method, string $path, mixed $handler)
- {
- $this->method = strtoupper($method);
- $this->path = $path;
- $this->handler = $handler;
-
- preg_match_all('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', $path, $names);
- $this->parameterNames = $names[1];
- $compiled = preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '([^/]+)', $path);
- $this->compiledPattern = '#^' . $compiled . '$#';
- }
-
- public function matches(string $method, string $path): bool
- {
- if (strtoupper($method) !== $this->method) {
- return false;
- }
-
- if (!preg_match($this->compiledPattern, $path, $matches)) {
- return false;
- }
-
- array_shift($matches);
- $this->parameters = [];
-
- foreach ($this->parameterNames as $index => $name) {
- $this->parameters[$name] = $matches[$index] ?? null;
- }
-
- return true;
- }
-
- public function dispatch(App $app): mixed
- {
- return $app->call($this->handler, $this->parameters);
- }
- }
|