Camel.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. namespace Knuckles\Camel;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Str;
  5. use Knuckles\Camel\Output\OutputEndpointData;
  6. use Knuckles\Scribe\Tools\Utils;
  7. use Symfony\Component\Yaml\Yaml;
  8. class Camel
  9. {
  10. public static function cacheDir(string $docsName = 'scribe'): string
  11. {
  12. return ".$docsName/endpoints.cache";
  13. }
  14. public static function camelDir(string $docsName = 'scribe'): string
  15. {
  16. return ".$docsName/endpoints";
  17. }
  18. /**
  19. * Load endpoints from the Camel files into groups (arrays).
  20. *
  21. * @param string $folder
  22. *
  23. * @return array[] Each array is a group with keys including `name` and `endpoints`.
  24. */
  25. public static function loadEndpointsIntoGroups(string $folder): array
  26. {
  27. $groups = [];
  28. self::loadEndpointsFromCamelFiles($folder, function (array $group) use (&$groups) {
  29. $groups[$group['name']] = $group;
  30. });
  31. return $groups;
  32. }
  33. /**
  34. * Load endpoints from the Camel files into a flat list of endpoint arrays.
  35. * Useful when we don't care about groups, but simply want to compare endpoints contents
  36. * to see if anything changed.
  37. *
  38. * @param string $folder
  39. *
  40. * @return array[] List of endpoint arrays.
  41. */
  42. public static function loadEndpointsToFlatPrimitivesArray(string $folder): array
  43. {
  44. $endpoints = [];
  45. self::loadEndpointsFromCamelFiles($folder, function (array $group) use (&$endpoints) {
  46. foreach ($group['endpoints'] as $endpoint) {
  47. $endpoints[] = $endpoint;
  48. }
  49. });
  50. return $endpoints;
  51. }
  52. public static function loadEndpointsFromCamelFiles(string $folder, callable $callback): void
  53. {
  54. $contents = Utils::listDirectoryContents($folder);
  55. foreach ($contents as $object) {
  56. // todo Flysystem v1 had items as arrays; v2 has objects.
  57. // v2 allows ArrayAccess, but when we drop v1 support (Laravel <9), we should switch to methods
  58. if (
  59. $object['type'] == 'file'
  60. && Str::endsWith(basename($object['path']), '.yaml')
  61. && !Str::startsWith(basename($object['path']), 'custom.')
  62. ) {
  63. $group = Yaml::parseFile($object['path']);
  64. $callback($group);
  65. }
  66. }
  67. }
  68. public static function loadUserDefinedEndpoints(string $folder): array
  69. {
  70. $contents = Utils::listDirectoryContents($folder);
  71. $userDefinedEndpoints = [];
  72. foreach ($contents as $object) {
  73. // Flysystem v1 had items as arrays; v2 has objects.
  74. // v2 allows ArrayAccess, but when we drop v1 support (Laravel <9), we should switch to methods
  75. if (
  76. $object['type'] == 'file'
  77. && Str::endsWith(basename($object['path']), '.yaml')
  78. && Str::startsWith(basename($object['path']), 'custom.')
  79. ) {
  80. $endpoints = Yaml::parseFile($object['path']);
  81. foreach (($endpoints ?: []) as $endpoint) {
  82. $userDefinedEndpoints[] = $endpoint;
  83. }
  84. }
  85. }
  86. return $userDefinedEndpoints;
  87. }
  88. public static function doesGroupContainEndpoint(array $group, OutputEndpointData $endpoint): bool
  89. {
  90. return boolval(Arr::first($group['endpoints'], function ($e) use ($endpoint) {
  91. return $e->endpointId() === $endpoint->endpointId();
  92. }));
  93. }
  94. /**
  95. * @param array[] $groupedEndpoints
  96. * @param array $configFileOrder The order for groups that users specified in their config file.
  97. *
  98. * @return array[]
  99. */
  100. public static function sortByConfigFileOrder(array $groupedEndpoints, array $configFileOrder): array
  101. {
  102. if (empty($configFileOrder)) {
  103. ksort($groupedEndpoints, SORT_NATURAL);
  104. return $groupedEndpoints;
  105. }
  106. // First, sort groups
  107. $groupsOrder = Utils::getTopLevelItemsFromMixedConfigList($configFileOrder);
  108. $groupsCollection = collect($groupedEndpoints);
  109. $wildcardPosition = array_search('*', $groupsOrder);
  110. if ($wildcardPosition !== false) {
  111. $promotedGroups = array_splice($groupsOrder, 0, $wildcardPosition);
  112. $demotedGroups = array_splice($groupsOrder, 1);
  113. $promotedOrderedGroups = $groupsCollection->filter(fn ($group, $groupName) => in_array($groupName, $promotedGroups))
  114. ->sortKeysUsing(self::getOrderListComparator($promotedGroups));
  115. $demotedOrderedGroups = $groupsCollection->filter(fn ($group, $groupName) => in_array($groupName, $demotedGroups))
  116. ->sortKeysUsing(self::getOrderListComparator($demotedGroups));
  117. $nonWildcardGroups = array_merge($promotedGroups, $demotedGroups);
  118. $wildCardOrderedGroups = $groupsCollection->filter(fn ($group, $groupName) => !in_array($groupName, $nonWildcardGroups))
  119. ->sortKeysUsing(self::getOrderListComparator($demotedGroups));
  120. $groupedEndpoints = $promotedOrderedGroups->merge($wildCardOrderedGroups)
  121. ->merge($demotedOrderedGroups);
  122. } else {
  123. $groupedEndpoints = $groupsCollection->sortKeysUsing(self::getOrderListComparator($groupsOrder));
  124. }
  125. return $groupedEndpoints->map(function (array $group, string $groupName) use ($configFileOrder) {
  126. $sortedEndpoints = collect($group['endpoints']);
  127. if (isset($configFileOrder[$groupName])) {
  128. // Second-level order list. Can contain endpoint or subgroup names
  129. $level2Order = Utils::getTopLevelItemsFromMixedConfigList($configFileOrder[$groupName]);
  130. $sortedEndpoints = $sortedEndpoints->sortBy(
  131. function (OutputEndpointData $e) use ($configFileOrder, $level2Order) {
  132. $endpointIdentifier = $e->httpMethods[0] . ' /' . $e->uri;
  133. // First, check if there's an ordering specified for the endpoint itself
  134. $indexOfEndpointInL2Order = array_search($endpointIdentifier, $level2Order);
  135. if ($indexOfEndpointInL2Order !== false) {
  136. return $indexOfEndpointInL2Order;
  137. }
  138. // Check if there's an ordering for the endpoint's subgroup
  139. $indexOfSubgroupInL2Order = array_search($e->metadata->subgroup, $level2Order);
  140. if ($indexOfSubgroupInL2Order !== false) {
  141. // There's a subgroup order; check if there's an endpoints order within that
  142. $orderOfEndpointsInSubgroup = $configFileOrder[$e->metadata->groupName][$e->metadata->subgroup] ?? [];
  143. $indexOfEndpointInSubGroup = array_search($endpointIdentifier, $orderOfEndpointsInSubgroup);
  144. return ($indexOfEndpointInSubGroup === false)
  145. ? $indexOfSubgroupInL2Order
  146. : ($indexOfSubgroupInL2Order + ($indexOfEndpointInSubGroup * 0.1));
  147. }
  148. return INF;
  149. },
  150. );
  151. }
  152. return [
  153. 'name' => $groupName,
  154. 'description' => $group['description'],
  155. 'endpoints' => $sortedEndpoints->all(),
  156. ];
  157. })->values()->all();
  158. }
  159. /**
  160. * Prepare endpoints to be turned into HTML.
  161. * Map them into OutputEndpointData DTOs, and sort them by the specified order in the config file.
  162. *
  163. * @param array<string,array[]> $groupedEndpoints
  164. *
  165. * @return array
  166. */
  167. public static function prepareGroupedEndpointsForOutput(array $groupedEndpoints, array $configFileOrder = []): array
  168. {
  169. $groups = array_map(function (array $group) {
  170. return [
  171. 'name' => $group['name'],
  172. 'description' => $group['description'],
  173. 'endpoints' => array_map(
  174. fn(array $endpoint) => OutputEndpointData::fromExtractedEndpointArray($endpoint), $group['endpoints']
  175. ),
  176. ];
  177. }, $groupedEndpoints);
  178. return Camel::sortByConfigFileOrder($groups, $configFileOrder);
  179. }
  180. /**
  181. * Given an $order list like ['first', 'second', ...], return a compare function that can be used to sort
  182. * a list of strings based on the order of items in $order.
  183. * Any strings not in the list are sorted with natural sort.
  184. *
  185. * @param array $order
  186. */
  187. public static function getOrderListComparator(array $order): \Closure
  188. {
  189. return function ($a, $b) use ($order) {
  190. $indexOfA = array_search($a, $order);
  191. $indexOfB = array_search($b, $order);
  192. // If both are in the $order list, compare them normally based on their position in the list
  193. if ($indexOfA !== false && $indexOfB !== false) {
  194. return $indexOfA <=> $indexOfB;
  195. }
  196. // If only A is in the $order list, then it must come before B.
  197. if ($indexOfA !== false) {
  198. return -1;
  199. }
  200. // If only B is in the $order list, then it must come before A.
  201. if ($indexOfB !== false) {
  202. return 1;
  203. }
  204. // If neither is present, fall back to natural sort
  205. return strnatcmp($a, $b);
  206. };
  207. }
  208. }