選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

51 行
1.2KB

  1. <?php
  2. declare(strict_types=1);
  3. namespace Core;
  4. class Route
  5. {
  6. protected string $method;
  7. protected string $path;
  8. protected mixed $handler;
  9. protected array $parameters = [];
  10. public function __construct(string $method, string $path, mixed $handler)
  11. {
  12. $this->method = strtoupper($method);
  13. $this->path = $path;
  14. $this->handler = $handler;
  15. }
  16. public function matches(string $method, string $path): bool
  17. {
  18. if (strtoupper($method) !== $this->method) {
  19. return false;
  20. }
  21. $routePattern = preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '([^/]+)', $this->path);
  22. $routePattern = '#^' . $routePattern . '$#';
  23. if (!preg_match($routePattern, $path, $matches)) {
  24. return false;
  25. }
  26. array_shift($matches);
  27. preg_match_all('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', $this->path, $names);
  28. $this->parameters = [];
  29. foreach ($names[1] as $index => $name) {
  30. $this->parameters[$name] = $matches[$index] ?? null;
  31. }
  32. return true;
  33. }
  34. public function dispatch(App $app): mixed
  35. {
  36. return $app->call($this->handler, $this->parameters);
  37. }
  38. }

Powered by TurnKey Linux.