RouteMatcher.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace Mpociot\ApiDoc\Tools;
  3. use Illuminate\Routing\Route;
  4. use Dingo\Api\Routing\RouteCollection;
  5. use Illuminate\Support\Facades\Route as RouteFacade;
  6. class RouteMatcher
  7. {
  8. public function getDingoRoutesToBeDocumented(array $routeRules)
  9. {
  10. return $this->getRoutesToBeDocumented($routeRules, true);
  11. }
  12. public function getLaravelRoutesToBeDocumented(array $routeRules)
  13. {
  14. return $this->getRoutesToBeDocumented($routeRules);
  15. }
  16. public function getRoutesToBeDocumented(array $routeRules, bool $usingDingoRouter = false)
  17. {
  18. $matchedRoutes = [];
  19. foreach ($routeRules as $routeRule) {
  20. $includes = $routeRule['include'] ?? [];
  21. $allRoutes = $this->getAllRoutes($usingDingoRouter, $routeRule['match']['versions'] ?? []);
  22. foreach ($allRoutes as $route) {
  23. if (is_array($route)) {
  24. $route = new LumenRouteAdapter($route);
  25. }
  26. if ($this->shouldExcludeRoute($route, $routeRule)) {
  27. continue;
  28. }
  29. if ($this->shouldIncludeRoute($route, $routeRule, $includes, $usingDingoRouter)) {
  30. $matchedRoutes[] = [
  31. 'route' => $route,
  32. 'apply' => $routeRule['apply'] ?? [],
  33. ];
  34. continue;
  35. }
  36. }
  37. }
  38. return $matchedRoutes;
  39. }
  40. private function getAllRoutes(bool $usingDingoRouter, array $versions = [])
  41. {
  42. if (! $usingDingoRouter) {
  43. return RouteFacade::getRoutes();
  44. }
  45. $allRouteCollections = app(\Dingo\Api\Routing\Router::class)->getRoutes();
  46. return collect($allRouteCollections)
  47. ->flatMap(function (RouteCollection $collection) {
  48. return $collection->getRoutes();
  49. })->toArray();
  50. }
  51. private function shouldIncludeRoute(Route $route, array $routeRule, array $mustIncludes, bool $usingDingoRouter)
  52. {
  53. $matchesVersion = $usingDingoRouter
  54. ? ! empty(array_intersect($route->versions(), $routeRule['match']['versions'] ?? []))
  55. : true;
  56. return str_is($mustIncludes, $route->getName())
  57. || str_is($mustIncludes, $route->uri())
  58. || (str_is($routeRule['match']['domains'] ?? [], $route->getDomain())
  59. && str_is($routeRule['match']['prefixes'] ?? [], $route->uri())
  60. && $matchesVersion);
  61. }
  62. private function shouldExcludeRoute(Route $route, array $routeRule)
  63. {
  64. $excludes = $routeRule['exclude'] ?? [];
  65. return str_is($excludes, $route->getName())
  66. || str_is($excludes, $route->uri());
  67. }
  68. }