RouteMatcher.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. $excludes = $routeRule['exclude'] ?? [];
  21. $includes = $routeRule['include'] ?? [];
  22. $allRoutes = $this->getAllRoutes($usingDingoRouter, $routeRule['match']['versions'] ?? []);
  23. foreach ($allRoutes as $route) {
  24. /** @var Route $route */
  25. if (in_array($route->getName(), $excludes)) {
  26. continue;
  27. }
  28. if ($this->shouldIncludeRoute($route, $routeRule, $includes, $usingDingoRouter)) {
  29. $matchedRoutes[] = [
  30. 'route' => $route,
  31. 'apply' => $routeRule['apply'] ?? [],
  32. ];
  33. continue;
  34. }
  35. }
  36. }
  37. return $matchedRoutes;
  38. }
  39. private function getAllRoutes(bool $usingDingoRouter, array $versions = [])
  40. {
  41. if (! $usingDingoRouter) {
  42. return RouteFacade::getRoutes();
  43. }
  44. $allRouteCollections = app(\Dingo\Api\Routing\Router::class)->getRoutes();
  45. return collect($allRouteCollections)
  46. ->flatMap(function (RouteCollection $collection) {
  47. return $collection->getRoutes();
  48. })->toArray();
  49. }
  50. private function shouldIncludeRoute(Route $route, array $routeRule, array $mustIncludes, bool $usingDingoRouter)
  51. {
  52. $matchesVersion = $usingDingoRouter
  53. ? ! empty(array_intersect($route->versions(), $routeRule['match']['versions'] ?? []))
  54. : true;
  55. return in_array($route->getName(), $mustIncludes)
  56. || (str_is($routeRule['match']['domains'] ?? [], $route->getDomain())
  57. && str_is($routeRule['match']['prefixes'] ?? [], $route->uri())
  58. && $matchesVersion);
  59. }
  60. }