Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

124 wiersze
2.7KB

  1. <?php
  2. namespace Framework\Routing;
  3. class Route
  4. {
  5. protected string $method;
  6. protected string $path;
  7. protected $handler;
  8. protected array $parameters = [];
  9. protected ?string $name = null;
  10. public function __construct(string $method, string $path, $handler)
  11. {
  12. $this->method = $method;
  13. $this->path = $path;
  14. $this->handler = $handler;
  15. }
  16. public function method(): string
  17. {
  18. return $this->method;
  19. }
  20. public function path(): string
  21. {
  22. return $this->path;
  23. }
  24. public function parameters(): array
  25. {
  26. return $this->parameters;
  27. }
  28. public function name(string $name = null)
  29. {
  30. if ($name) {
  31. $this->name = $name;
  32. return $this;
  33. }
  34. return $this->name;
  35. }
  36. public function matches(string $method, string $path): bool
  37. {
  38. if (
  39. $this->method === $method
  40. && $this->path === $path
  41. ) {
  42. return true;
  43. }
  44. $parameterNames = [];
  45. $pattern = $this->normalisePath($this->path);
  46. $pattern = preg_replace_callback('#{([^}]+)}/#', function (array $found) use (&$parameterNames) {
  47. array_push($parameterNames, rtrim($found[1], '?'));
  48. if (str_ends_with($found[1], '?')) {
  49. return '([^/]*)(?:/?)';
  50. }
  51. return '([^/]+)/';
  52. }, $pattern);
  53. if (
  54. !str_contains($pattern, '+')
  55. && !str_contains($pattern, '*')
  56. ) {
  57. return false;
  58. }
  59. preg_match_all("#{$pattern}#", $this->normalisePath($path), $matches);
  60. $parameterValues = [];
  61. if (count($matches[1]) > 0) {
  62. foreach ($matches[1] as $value) {
  63. if ($value) {
  64. array_push($parameterValues, $value);
  65. continue;
  66. }
  67. array_push($parameterValues, null);
  68. }
  69. $emptyValues = array_fill(0, count($parameterNames), false);
  70. $parameterValues += $emptyValues;
  71. $this->parameters = array_combine($parameterNames, $parameterValues);
  72. return true;
  73. }
  74. return false;
  75. }
  76. private function normalisePath(string $path): string
  77. {
  78. $path = trim($path, '/');
  79. $path = "/{$path}/";
  80. $path = preg_replace('/[\/]{2,}/', '/', $path);
  81. return $path;
  82. }
  83. public function dispatch()
  84. {
  85. if (is_array($this->handler)) {
  86. [$class, $method] = $this->handler;
  87. if (is_string($class)) {
  88. return app()->call([new $class, $method]);
  89. }
  90. return app()->call([$class, $method]);
  91. }
  92. return app()->call($this->handler);
  93. }
  94. }

Powered by TurnKey Linux.