RouteCollector.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\RpcServer\Router;
  12. use FastRoute\DataGenerator;
  13. use FastRoute\RouteParser;
  14. use Hyperf\HttpServer\Router\Handler;
  15. class RouteCollector
  16. {
  17. protected string $currentGroupPrefix;
  18. protected array $currentGroupOptions = [];
  19. /**
  20. * Constructs a route collector.
  21. */
  22. public function __construct(protected RouteParser $routeParser, protected DataGenerator $dataGenerator)
  23. {
  24. $this->currentGroupPrefix = '';
  25. }
  26. /**
  27. * Adds a route to the collection.
  28. *
  29. * The syntax used in the $route string depends on the used route parser.
  30. *
  31. * @param mixed $handler
  32. */
  33. public function addRoute(string $route, $handler, array $options = [])
  34. {
  35. $route = $this->currentGroupPrefix . $route;
  36. $routeDatas = $this->routeParser->parse($route);
  37. foreach ($routeDatas as $routeData) {
  38. $this->dataGenerator->addRoute('POST', $routeData, new Handler($handler, $route));
  39. }
  40. }
  41. /**
  42. * Create a route group with a common prefix.
  43. *
  44. * All routes created in the passed callback will have the given group prefix prepended.
  45. *
  46. * @param string $prefix
  47. */
  48. public function addGroup($prefix, callable $callback, array $options = [])
  49. {
  50. $previousGroupPrefix = $this->currentGroupPrefix;
  51. $this->currentGroupPrefix = $previousGroupPrefix . $prefix;
  52. $callback($this);
  53. $this->currentGroupPrefix = $previousGroupPrefix;
  54. }
  55. /**
  56. * Returns the collected route data, as provided by the data generator.
  57. *
  58. * @return array
  59. */
  60. public function getData()
  61. {
  62. return $this->dataGenerator->getData();
  63. }
  64. }