1
0

Route.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php declare(strict_types = 1);
  2. namespace Formstack\FormAutoScaffold\Framework;
  3. class Route
  4. {
  5. private array $routes = [];
  6. public array $matchedRoute = [];
  7. public function __construct(
  8. private string $route,
  9. private string $method
  10. ) {
  11. $this->collectDefinedRoutes();
  12. $this->matchedRoute = $this->matchRoute($route, $method);
  13. }
  14. private function collectDefinedRoutes()
  15. {
  16. foreach (get_defined_functions()['user'] as $fnName) {
  17. $ref = new \ReflectionFunction($fnName);
  18. foreach ($ref->getAttributes() as $attr) {
  19. $name = $attr->getName();
  20. if ($name === 'Route') {
  21. $args = $attr->getArguments();
  22. $this->routes[$args[0]] = [
  23. $fnName,
  24. $args[1]
  25. ];
  26. }
  27. }
  28. }
  29. }
  30. private function matchRoute(string $route, string $method): array
  31. {
  32. foreach ($this->routes as $definedRoute => $fn) {
  33. if (
  34. $definedRoute === $route
  35. && (
  36. (
  37. is_array($fn[1])
  38. && in_array($method, $fn[1])
  39. )
  40. || $fn[1] === $method
  41. )
  42. ) {
  43. return $fn;
  44. }
  45. }
  46. return [];
  47. }
  48. }