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