-
-
Notifications
You must be signed in to change notification settings - Fork 355
Expand file tree
/
Copy pathOpenAPISpecWriter.php
More file actions
592 lines (525 loc) · 21.7 KB
/
Copy pathOpenAPISpecWriter.php
File metadata and controls
592 lines (525 loc) · 21.7 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
<?php
namespace Knuckles\Scribe\Writing;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Knuckles\Camel\Camel;
use Knuckles\Camel\Extraction\Response;
use Knuckles\Camel\Output\OutputEndpointData;
use Knuckles\Camel\Output\Parameter;
use Knuckles\Scribe\Extracting\ParamHelpers;
use Knuckles\Scribe\Tools\DocumentationConfig;
use Knuckles\Scribe\Tools\Utils;
use function array_map;
class OpenAPISpecWriter
{
use ParamHelpers;
const SPEC_VERSION = '3.0.3';
private DocumentationConfig $config;
public function __construct(DocumentationConfig $config = null)
{
$this->config = $config ?: new DocumentationConfig(config('scribe', []));
}
/**
* See https://swagger.io/specification/
*
* @param array[] $groupedEndpoints
*
* @return array
*/
public function generateSpecContent(array $groupedEndpoints): array
{
return array_merge([
'openapi' => self::SPEC_VERSION,
'info' => [
'title' => $this->config->get('title') ?: config('app.name', ''),
'description' => $this->config->get('description', ''),
'version' => '1.0.0',
],
'servers' => [
[
'url' => rtrim($this->config->get('base_url') ?? config('app.url'), '/'),
],
],
'paths' => $this->generatePathsSpec($groupedEndpoints),
'tags' => array_values(array_map(function (array $group) {
return [
'name' => $group['name'],
'description' => $group['description'],
];
}, $groupedEndpoints)),
], $this->generateSecurityPartialSpec());
}
/**
* @param array[] $groupedEndpoints
*
* @return mixed
*/
protected function generatePathsSpec(array $groupedEndpoints)
{
$allEndpoints = collect($groupedEndpoints)->map->endpoints->flatten(1);
// OpenAPI groups endpoints by path, then method
$groupedByPath = $allEndpoints->groupBy(function ($endpoint) {
$path = str_replace("?}", "}", $endpoint->uri); // Remove optional parameters indicator in path
return '/' . ltrim($path, '/');
});
return $groupedByPath->mapWithKeys(function (Collection $endpoints, $path) use ($groupedEndpoints) {
$operations = $endpoints->mapWithKeys(function (OutputEndpointData $endpoint) use ($groupedEndpoints) {
$spec = [
'summary' => $endpoint->metadata->title,
'operationId' => $this->operationId($endpoint),
'description' => $endpoint->metadata->description,
'parameters' => $this->generateEndpointParametersSpec($endpoint),
'responses' => $this->generateEndpointResponsesSpec($endpoint),
'tags' => [Arr::first($groupedEndpoints, function ($group) use ($endpoint) {
return Camel::doesGroupContainEndpoint($group, $endpoint);
})['name']],
];
if (count($endpoint->bodyParameters)) {
$spec['requestBody'] = $this->generateEndpointRequestBodySpec($endpoint);
}
if (!$endpoint->metadata->authenticated) {
// Make sure to exclude non-auth endpoints from auth
$spec['security'] = [];
}
return [strtolower($endpoint->httpMethods[0]) => $spec];
});
$pathItem = $operations;
// Placing all URL parameters at the path level, since it's the same path anyway
if (count($endpoints[0]->urlParameters)) {
$parameters = [];
/**
* @var string $name
* @var Parameter $details
*/
foreach ($endpoints[0]->urlParameters as $name => $details) {
$parameterData = [
'in' => 'path',
'name' => $name,
'description' => $details->description,
'example' => $details->example,
// Currently, OAS requires path parameters to be required
'required' => true,
'schema' => [
'type' => $details->type,
],
];
// Workaround for optional parameters
if (empty($details->required)) {
$parameterData['description'] = rtrim('Optional parameter. ' . $parameterData['description']);
$parameterData['examples'] = [
'omitted' => [
'summary' => 'When the value is omitted',
'value' => '',
],
];
if ($parameterData['example'] !== null) {
$parameterData['examples']['present'] = [
'summary' => 'When the value is present',
'value' => $parameterData['example'],
];
}
// Can't have `example` and `examples`
unset($parameterData['example']);
}
$parameters[] = $parameterData;
}
$pathItem['parameters'] = $parameters; // @phpstan-ignore-line
}
return [$path => $pathItem];
})->toArray();
}
/**
* Add query parameters and headers.
*
* @param OutputEndpointData $endpoint
*
* @return array<int, array<string,mixed>>
*/
protected function generateEndpointParametersSpec(OutputEndpointData $endpoint): array
{
$parameters = [];
if (count($endpoint->queryParameters)) {
/**
* @var string $name
* @var Parameter $details
*/
foreach ($endpoint->queryParameters as $name => $details) {
$parameterData = [
'in' => 'query',
'name' => $name,
'description' => $details->description,
'example' => $details->example,
'required' => $details->required,
'schema' => $this->generateFieldData($details),
];
$parameters[] = $parameterData;
}
}
if (count($endpoint->headers)) {
foreach ($endpoint->headers as $name => $value) {
if (in_array(strtolower($name), ['content-type', 'accept', 'authorization']))
// These headers are not allowed in the spec.
// https://swagger.io/docs/specification/describing-parameters/#header-parameters
continue;
$parameters[] = [
'in' => 'header',
'name' => $name,
'description' => '',
'example' => $value,
'schema' => [
'type' => 'string',
],
];
}
}
return $parameters;
}
protected function generateEndpointRequestBodySpec(OutputEndpointData $endpoint)
{
$body = [];
if (count($endpoint->bodyParameters)) {
$schema = [
'type' => 'object',
'properties' => [],
];
$hasRequiredParameter = false;
$hasFileParameter = false;
foreach ($endpoint->nestedBodyParameters as $name => $details) {
if ($name === "[]") { // Request body is an array
$hasRequiredParameter = true;
$schema = $this->generateFieldData($details);
break;
}
if ($details['required']) {
$hasRequiredParameter = true;
// Don't declare this earlier.
// The spec doesn't allow for an empty `required` array. Must have something there.
$schema['required'][] = $name;
}
if ($details['type'] === 'file') {
$hasFileParameter = true;
}
$fieldData = $this->generateFieldData($details);
$schema['properties'][$name] = $fieldData;
}
// We remove 'properties' if the request body is an array, so we need to check if it's still there
if (array_key_exists('properties', $schema)) {
$schema['properties'] = $this->objectIfEmpty($schema['properties']);
}
$body['required'] = $hasRequiredParameter;
if ($hasFileParameter) {
// If there are file parameters, content type changes to multipart
$contentType = 'multipart/form-data';
} elseif (isset($endpoint->headers['Content-Type'])) {
$contentType = $endpoint->headers['Content-Type'];
} else {
$contentType = 'application/json';
}
$body['content'][$contentType]['schema'] = $schema;
}
// return object rather than empty array, so can get properly serialised as object
return $this->objectIfEmpty($body);
}
protected function generateEndpointResponsesSpec(OutputEndpointData $endpoint)
{
// See https://swagger.io/docs/specification/describing-responses/
$responses = [];
foreach ($endpoint->responses as $response) {
// OpenAPI groups responses by status code
// Only one response type per status code, so only the last one will be used
if (intval($response->status) === 204) {
// Must not add content for 204
$responses[204] = [
'description' => $this->getResponseDescription($response),
];
} else {
$responses[$response->status] = [
'description' => $this->getResponseDescription($response),
'content' => $this->generateResponseContentSpec($response->content, $endpoint),
];
}
}
// return object rather than empty array, so can get properly serialised as object
return $this->objectIfEmpty($responses);
}
protected function getResponseDescription(Response $response): string
{
if (Str::startsWith($response->content, "<<binary>>")) {
return trim(str_replace("<<binary>>", "", $response->content));
}
$description = strval($response->description);
// Don't include the status code in description; see https://github.com/knuckleswtf/scribe/issues/271
if (preg_match("/\d{3},\s+(.+)/", $description, $matches)) {
$description = $matches[1];
} else if ($description === strval($response->status)) {
$description = '';
}
return $description;
}
protected function generateResponseContentSpec(?string $responseContent, OutputEndpointData $endpoint)
{
if (Str::startsWith($responseContent, '<<binary>>')) {
return [
'application/octet-stream' => [
'schema' => [
'type' => 'string',
'format' => 'binary',
],
],
];
}
if ($responseContent === null) {
return [
'application/json' => [
'schema' => [
'type' => 'object',
// See https://swagger.io/docs/specification/data-models/data-types/#null
'nullable' => true,
],
],
];
}
$decoded = json_decode($responseContent);
if ($decoded === null) { // Decoding failed, so we return the content string as is
return [
'text/plain' => [
'schema' => [
'type' => 'string',
'example' => $responseContent,
],
],
];
}
switch ($type = gettype($decoded)) {
case 'string':
case 'boolean':
case 'integer':
case 'double':
return [
'application/json' => [
'schema' => [
'type' => $type === 'double' ? 'number' : $type,
'example' => $decoded,
],
],
];
case 'array':
if (!count($decoded)) {
// empty array
return [
'application/json' => [
'schema' => [
'type' => 'array',
'items' => [
'type' => 'object', // No better idea what to put here
],
'example' => $decoded,
],
],
];
}
// Non-empty array
return [
'application/json' => [
'schema' => [
'type' => 'array',
'items' => [
'type' => $this->convertScribeOrPHPTypeToOpenAPIType(gettype($decoded[0])),
],
'example' => $decoded,
],
],
];
case 'object':
$properties = collect($decoded)->mapWithKeys(function ($value, $key) use ($endpoint) {
return [$key => $this->generateSchemaForValue($value, $endpoint, $key)];
})->toArray();
return [
'application/json' => [
'schema' => [
'type' => 'object',
'example' => $decoded,
'properties' => $this->objectIfEmpty($properties),
],
],
];
}
}
protected function generateSecurityPartialSpec(): array
{
$isApiAuthed = $this->config->get('auth.enabled', false);
if (!$isApiAuthed) {
return [];
}
$location = $this->config->get('auth.in');
$parameterName = $this->config->get('auth.name');
$description = $this->config->get('auth.extra_info');
$scheme = match ($location) {
'query', 'header' => [
'type' => 'apiKey',
'name' => $parameterName,
'in' => $location,
'description' => $description,
],
'bearer', 'basic' => [
'type' => 'http',
'scheme' => $location,
'description' => $description,
],
default => [],
};
return [
// All security schemes must be registered in `components.securitySchemes`...
'components' => [
'securitySchemes' => [
// 'default' is an arbitrary name for the auth scheme. Can be anything, really.
'default' => $scheme,
],
],
// ...and then can be applied in `security`
'security' => [
[
'default' => [],
],
],
];
}
protected function convertScribeOrPHPTypeToOpenAPIType($type)
{
return match ($type) {
'float', 'double' => 'number',
'NULL' => 'string',
default => $type,
};
}
/**
* @param Parameter|array $field
*
* @return array
*/
public function generateFieldData($field): array
{
if (is_array($field)) {
$field = new Parameter($field);
}
$fieldData = [];
if ($field->type === 'file') {
// See https://swagger.io/docs/specification/describing-request-body/file-upload/
$fieldData = [
'type' => 'string',
'format' => 'binary',
'description' => $field->description ?: '',
];
} else if (Utils::isArrayType($field->type)) {
$baseType = Utils::getBaseTypeFromArrayType($field->type);
$baseItem = ($baseType === 'file') ? [
'type' => 'string',
'format' => 'binary',
] : ['type' => $baseType];
$fieldData = [
'type' => 'array',
'description' => $field->description ?: '',
'example' => $field->example,
'items' => Utils::isArrayType($baseType)
? $this->generateFieldData([
'name' => '',
'type' => $baseType,
'example' => ($field->example ?: [null])[0],
])
: $baseItem,
];
if (str_replace('[]', "", $field->type) === 'file') {
// Don't include example for file params in OAS; it's hard to translate it correctly
unset($fieldData['example']);
}
if ($baseType === 'object' && !empty($field->__fields)) {
if ($fieldData['items']['type'] === 'object') {
$fieldData['items']['properties'] = [];
}
foreach ($field->__fields as $fieldSimpleName => $subfield) {
$fieldData['items']['properties'][$fieldSimpleName] = $this->generateFieldData($subfield);
if ($subfield['required']) {
$fieldData['items']['required'][] = $fieldSimpleName;
}
}
}
} else if ($field->type === 'object') {
$fieldData = [
'type' => 'object',
'description' => $field->description ?: '',
'example' => $field->example,
'properties' => $this->objectIfEmpty(collect($field->__fields)->mapWithKeys(function ($subfield, $subfieldName) {
return [$subfieldName => $this->generateFieldData($subfield)];
})->all()),
];
} else {
$fieldData = [
'type' => static::normalizeTypeName($field->type),
'description' => $field->description ?: '',
'example' => $field->example,
];
if (!empty($field->enumValues)) {
$fieldData['enum'] = $field->enumValues;
}
}
if (isset($field['required']) && !$field['required']) {
$fieldData['nullable'] = true;
}
return $fieldData;
}
protected function operationId(OutputEndpointData $endpoint): string
{
if ($endpoint->metadata->title) return preg_replace('/[^\w+]/', '', Str::camel($endpoint->metadata->title));
$parts = preg_split('/[^\w+]/', $endpoint->uri, -1, PREG_SPLIT_NO_EMPTY);
return Str::lower($endpoint->httpMethods[0]) . join('', array_map(fn($part) => ucfirst($part), $parts));
}
/**
* Given an array, return an object if the array is empty. To be used with fields that are
* required by OpenAPI spec to be objects, since empty arrays get serialised as [].
*/
protected function objectIfEmpty(array $field): array|\stdClass
{
return count($field) > 0 ? $field : new \stdClass();
}
/**
* Given a value, generate the schema for it. The schema consists of: {type:, example:, properties: (if value is an
* object)}, and possibly a description for each property. The $endpoint and $path are used for looking up response
* field descriptions.
*/
public function generateSchemaForValue(mixed $value, OutputEndpointData $endpoint, string $path): array
{
if ($value instanceof \stdClass) {
$value = (array)$value;
$properties = [];
// Recurse into the object
foreach ($value as $subField => $subValue) {
$subFieldPath = sprintf('%s.%s', $path, $subField);
$properties[$subField] = $this->generateSchemaForValue($subValue, $endpoint, $subFieldPath);
}
return [
'type' => 'object',
'properties' => $this->objectIfEmpty($properties),
];
}
$schema = [
'type' => $this->convertScribeOrPHPTypeToOpenAPIType(gettype($value)),
'example' => $value,
];
if (isset($endpoint->responseFields[$path]->description)) {
$schema['description'] = $endpoint->responseFields[$path]->description;
}
if ($schema['type'] === 'array' && !empty($value)) {
$schema['example'] = json_decode(json_encode($schema['example']), true); // Convert stdClass to array
$sample = $value[0];
$typeOfEachItem = $this->convertScribeOrPHPTypeToOpenAPIType(gettype($sample));
$schema['items']['type'] = $typeOfEachItem;
if ($typeOfEachItem === 'object') {
$schema['items']['properties'] = collect($sample)->mapWithKeys(function ($v, $k) use ($endpoint, $path) {
return [$k => $this->generateSchemaForValue($v, $endpoint, "$path.$k")];
})->toArray();
}
}
return $schema;
}
}