Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

53 řádky
1.3KB

  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 $compiledPattern;
  11. protected array $parameterNames = [];
  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. preg_match_all('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', $path, $names);
  18. $this->parameterNames = $names[1];
  19. $compiled = preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '([^/]+)', $path);
  20. $this->compiledPattern = '#^' . $compiled . '$#';
  21. }
  22. public function matches(string $method, string $path): bool
  23. {
  24. if (strtoupper($method) !== $this->method) {
  25. return false;
  26. }
  27. if (!preg_match($this->compiledPattern, $path, $matches)) {
  28. return false;
  29. }
  30. array_shift($matches);
  31. $this->parameters = [];
  32. foreach ($this->parameterNames as $index => $name) {
  33. $this->parameters[$name] = $matches[$index] ?? null;
  34. }
  35. return true;
  36. }
  37. public function dispatch(App $app): mixed
  38. {
  39. return $app->call($this->handler, $this->parameters);
  40. }
  41. }

Powered by TurnKey Linux.