Camel.php 9.4 KB

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