Skip to content

Commit f9cd077

Browse files
s-shiryaevshalvah
andauthored
Add support for arrays of objects in OpenAPI response generation (#1021)
Fixes #1007 Co-authored-by: Shalvah <shalvah@users.noreply.github.com>
1 parent 9569a68 commit f9cd077

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

src/Writing/OpenApiSpecGenerators/BaseGenerator.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,26 @@ protected function generateResponseContentSpec(?string $responseContent, OutputE
365365
}
366366

367367
// Non-empty array
368+
if (is_object($decoded[0])) {
369+
// If the first item is an object, we assume it's an array of objects'
370+
$properties = collect($decoded[0])->mapWithKeys(function ($value, $key) use ($endpoint) {
371+
return [$key => $this->generateSchemaForResponseValue($value, $endpoint, $key)];
372+
})->toArray();
373+
374+
return [
375+
'application/json' => [
376+
'schema' => [
377+
'type' => 'array',
378+
'items' => [
379+
'type' => $this->convertScribeOrPHPTypeToOpenAPIType(gettype($decoded[0])),
380+
'properties' => $this->objectIfEmpty($properties),
381+
],
382+
'example' => $decoded,
383+
],
384+
],
385+
];
386+
}
387+
368388
return [
369389
'application/json' => [
370390
'schema' => [

tests/Unit/OpenAPISpecWriterTest.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,52 @@ public function adds_responses_correctly_as_responses_on_operation_object()
680680
], $results['paths']['/path2']['put']['responses']);
681681
}
682682

683+
/** @test */
684+
public function adds_responses_correctly_as_array_of_objects()
685+
{
686+
$endpointData1 = $this->createMockEndpointData([
687+
'httpMethods' => ['GET'],
688+
'uri' => '/path1',
689+
'responses' => [
690+
[
691+
'status' => 200,
692+
'description' => 'Successfully.',
693+
'content' => '[{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}]',
694+
],
695+
],
696+
]);
697+
$groups = [$this->createGroup([$endpointData1])];
698+
699+
$results = $this->generate($groups);
700+
701+
$this->assertCount(1, $results['paths']['/path1']['get']['responses']);
702+
$this->assertArraySubset([
703+
'200' => [
704+
'description' => 'Successfully.',
705+
'content' => [
706+
'application/json' => [
707+
'schema' => [
708+
'type' => 'array',
709+
'items' => [
710+
'type' => 'object',
711+
'properties' => [
712+
'id' => [
713+
'type' => 'integer',
714+
'example' => 1,
715+
],
716+
'name' => [
717+
'type' => 'string',
718+
'example' => 'John',
719+
],
720+
]
721+
],
722+
],
723+
],
724+
],
725+
],
726+
], $results['paths']['/path1']['get']['responses']);
727+
}
728+
683729
/** @test */
684730
public function adds_required_fields_on_array_of_objects()
685731
{

0 commit comments

Comments
 (0)