You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.1KB

  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. protected ?string $middleware = null;
  11. protected ?string $requiredPermission = null;
  12. public function __construct(string $method, string $path, mixed $handler)
  13. {
  14. $this->method = strtoupper($method);
  15. $this->path = $path;
  16. $this->handler = $handler;
  17. }
  18. // ── Fluent middleware / permission builders ───────────────────────────────
  19. public function middleware(string $name): self
  20. {
  21. $this->middleware = $name;
  22. return $this;
  23. }
  24. public function permission(string $permission): self
  25. {
  26. $this->requiredPermission = $permission;
  27. return $this;
  28. }
  29. public function getMiddleware(): ?string
  30. {
  31. return $this->middleware;
  32. }
  33. public function getRequiredPermission(): ?string
  34. {
  35. return $this->requiredPermission;
  36. }
  37. // ── Matching ──────────────────────────────────────────────────────────────
  38. public function matches(string $method, string $path): bool
  39. {
  40. if (strtoupper($method) !== $this->method) {
  41. return false;
  42. }
  43. $routePattern = preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '([^/]+)', $this->path);
  44. $routePattern = '#^' . $routePattern . '$#';
  45. if (!preg_match($routePattern, $path, $matches)) {
  46. return false;
  47. }
  48. array_shift($matches);
  49. preg_match_all('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', $this->path, $names);
  50. $this->parameters = [];
  51. foreach ($names[1] as $index => $name) {
  52. $this->parameters[$name] = $matches[$index] ?? null;
  53. }
  54. return true;
  55. }
  56. public function dispatch(App $app): mixed
  57. {
  58. return $app->call($this->handler, $this->parameters);
  59. }
  60. }

Powered by TurnKey Linux.