-
-
Notifications
You must be signed in to change notification settings - Fork 356
Expand file tree
/
Copy pathGetFromLaravelAPI.php
More file actions
223 lines (185 loc) · 8.84 KB
/
Copy pathGetFromLaravelAPI.php
File metadata and controls
223 lines (185 loc) · 8.84 KB
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
<?php
namespace Knuckles\Scribe\Extracting\Strategies\UrlParameters;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Knuckles\Camel\Extraction\ExtractedEndpointData;
use Knuckles\Scribe\Extracting\ParamHelpers;
use Knuckles\Scribe\Extracting\Shared\UrlParamsNormalizer;
use Knuckles\Scribe\Extracting\Strategies\Strategy;
use Knuckles\Scribe\Tools\Utils;
use Throwable;
class GetFromLaravelAPI extends Strategy
{
use ParamHelpers;
public function __invoke(ExtractedEndpointData $endpointData, array $routeRules = []): ?array
{
$parameters = [];
$path = $endpointData->uri;
preg_match_all('/\{(.*?)\}/', $path, $matches);
foreach ($matches[1] as $match) {
$isOptional = Str::endsWith($match, '?');
$name = rtrim($match, '?');
$parameters[$name] = [
'name' => $name,
'description' => $this->inferUrlParamDescription($endpointData->uri, $name),
'required' => !$isOptional,
];
}
$parameters = $this->inferBetterTypesAndExamplesForEloquentUrlParameters($parameters, $endpointData);
$parameters = $this->inferBetterTypesAndExamplesForEnumUrlParameters($parameters, $endpointData);
$parameters = $this->setTypesAndExamplesForOthers($parameters, $endpointData);
return $parameters;
}
protected function inferUrlParamDescription(string $url, string $paramName): string
{
// If $url is sth like /users/{id}, return "The ID of the user."
// If $url is sth like /anything/{user_id}, return "The ID of the user."
$strategies = collect(["id", "slug"])->map(function ($name) {
$friendlyName = $name === 'id' ? "ID" : $name;
return function ($url, $paramName) use ($name, $friendlyName) {
if ($paramName == $name) {
$thing = $this->getNameOfUrlThing($url, $paramName);
return "The $friendlyName of the $thing.";
} else if (Str::is("*_$name", $paramName)) {
$thing = str_replace(["_", "-"], " ", str_replace("_$name", '', $paramName));
return "The $friendlyName of the $thing.";
}
};
})->toArray();
// If $url is sth like /categories/{category}, return "The category."
$strategies[] = function ($url, $paramName) {
$thing = $this->getNameOfUrlThing($url, $paramName);
if ($thing === $paramName) {
return "The $thing.";
}
};
foreach ($strategies as $strategy) {
if ($inferred = $strategy($url, $paramName)) {
return $inferred;
}
}
return '';
}
protected function inferBetterTypesAndExamplesForEloquentUrlParameters(array $parameters, ExtractedEndpointData $endpointData): array
{
//We'll gather Eloquent model instances that can be linked to a URl parameter
$modelInstances = [];
// First, any bound models
// Eg if route is /users/{id}, and (User $user) model is typehinted on method
// If User model has `id` as an integer, then {id} param should be an integer
$typeHintedEloquentModels = UrlParamsNormalizer::getTypeHintedEloquentModels($endpointData->method);
foreach ($typeHintedEloquentModels as $argumentName => $modelInstance) {
$routeKey = $endpointData->route->bindingFields()[$argumentName] ?? $modelInstance->getRouteKeyName();
// Find the param name. In our normalized URL, argument $user might be param {user}, or {user_id}, or {id},
if (isset($parameters[$argumentName])) {
$paramName = $argumentName;
} else if (isset($parameters["{$argumentName}_$routeKey"])) {
$paramName = "{$argumentName}_$routeKey";
} else if (isset($parameters[$routeKey])) {
$paramName = $routeKey;
} else {
continue;
}
$modelInstances[$paramName] = $modelInstance;
}
// Next, non-Eloquent-bound parameters. They might still be Eloquent models, but model binding wasn't used.
foreach ($parameters as $name => $data) {
if (isset($data['type'])) continue;
// If the url is /things/{id}, try to find a Thing model
$urlThing = $this->getNameOfUrlThing($endpointData->uri, $name);
if ($urlThing && ($modelInstance = $this->findModelFromUrlThing($urlThing))) {
$modelInstances[$name] = $modelInstance;
}
}
// Now infer.
foreach ($modelInstances as $paramName => $modelInstance) {
// If the routeKey is the same as the primary key in the database, use the PK's type.
$routeKey = in_array($paramName, $endpointData->route->bindingFields()) ? $paramName : $modelInstance->getRouteKeyName();;
$type = $modelInstance->getKeyName() === $routeKey ? static::normalizeTypeName($modelInstance->getKeyType()) : 'string';
$parameters[$paramName]['type'] = $type;
try {
$parameters[$paramName]['example'] = $modelInstance::first()->$routeKey ?? null;
} catch (Throwable) {
$parameters[$paramName]['example'] = null;
}
}
return $parameters;
}
protected function inferBetterTypesAndExamplesForEnumUrlParameters(array $parameters, ExtractedEndpointData $endpointData): array
{
$typeHintedEnums = UrlParamsNormalizer::getTypeHintedEnums($endpointData->method);
foreach ($typeHintedEnums as $argumentName => $enum) {
$parameters[$argumentName]['type'] = static::normalizeTypeName($enum->getBackingType());
try {
$parameters[$argumentName]['example'] = $enum->getCases()[0]->getBackingValue();
} catch (Throwable) {
$parameters[$argumentName]['example'] = null;
}
}
return $parameters;
}
protected function setTypesAndExamplesForOthers(array $parameters, ExtractedEndpointData $endpointData): array
{
foreach ($parameters as $name => $parameter) {
if (empty($parameter['type'])) {
$parameters[$name]['type'] = "string";
}
if (($parameter['example'] ?? null) === null) {
// If the user explicitly set a `where()` constraint, use that to refine examples
$parameterRegex = $endpointData->route->wheres[$name] ?? null;
$parameters[$name]['example'] = $parameterRegex
? $this->castToType($this->getFaker()->regexify($parameterRegex), $parameters[$name]['type'])
: $this->generateDummyValue($parameters[$name]['type'], hints: ['name' => $name]);
}
}
return $parameters;
}
/**
* Given a URL parameter $paramName, extract the "thing" that comes before it. eg::
* - /<whatever>/things/{paramName} -> "thing"
* - animals/cats/{id} -> "cat"
* - users/{user_id}/contracts -> "user"
*
* @param string $url
* @param string $paramName
* @param string|null $alternateParamName A second paramName to try, if the original paramName isn't in the URL.
*
* @return string|null
*/
protected function getNameOfUrlThing(string $url, string $paramName, ?string $alternateParamName = null): ?string
{
$parts = explode("/", $url);
if (count($parts) === 1) return null; // URL was "/{thing}"
$paramIndex = array_search("{{$paramName}}", $parts);
if ($paramIndex === false) {
$paramIndex = array_search("{{$alternateParamName}}", $parts);
}
if ($paramIndex === false || $paramIndex === 0) return null;
$things = $parts[$paramIndex - 1];
// Replace underscores/hyphens, so "side_projects" becomes "side project"
return str_replace(["_", "-"], " ", Str::singular($things));
}
/**
* Given a URL "thing", like the "cat" in /cats/{id}, try to locate a Cat model.
*
* @param string $urlThing
*
* @return Model|null
*/
protected function findModelFromUrlThing(string $urlThing): ?Model
{
$className = str_replace(['-', '_', ' '], '', Str::title($urlThing));
$rootNamespace = app()->getNamespace();
if (class_exists($class = "{$rootNamespace}Models\\" . $className, autoload: false)
// For the heathens that don't use a Models\ directory
|| class_exists($class = $rootNamespace . $className, autoload: false)) {
try {
$instance = new $class;
} catch (\Error) { // It might be an enum or some other non-instantiable class
return null;
}
return $instance instanceof Model ? $instance : null;
}
return null;
}
}