diff --git a/src/Writing/OpenApiSpecGenerators/BaseGenerator.php b/src/Writing/OpenApiSpecGenerators/BaseGenerator.php index 35ff1146..d149572d 100644 --- a/src/Writing/OpenApiSpecGenerators/BaseGenerator.php +++ b/src/Writing/OpenApiSpecGenerators/BaseGenerator.php @@ -365,6 +365,26 @@ protected function generateResponseContentSpec(?string $responseContent, OutputE } // Non-empty array + if (is_object($decoded[0])) { + // If the first item is an object, we assume it's an array of objects' + $properties = collect($decoded[0])->mapWithKeys(function ($value, $key) use ($endpoint) { + return [$key => $this->generateSchemaForResponseValue($value, $endpoint, $key)]; + })->toArray(); + + return [ + 'application/json' => [ + 'schema' => [ + 'type' => 'array', + 'items' => [ + 'type' => $this->convertScribeOrPHPTypeToOpenAPIType(gettype($decoded[0])), + 'properties' => $this->objectIfEmpty($properties), + ], + 'example' => $decoded, + ], + ], + ]; + } + return [ 'application/json' => [ 'schema' => [ diff --git a/tests/Unit/OpenAPISpecWriterTest.php b/tests/Unit/OpenAPISpecWriterTest.php index 99398d19..dc82a173 100644 --- a/tests/Unit/OpenAPISpecWriterTest.php +++ b/tests/Unit/OpenAPISpecWriterTest.php @@ -680,6 +680,52 @@ public function adds_responses_correctly_as_responses_on_operation_object() ], $results['paths']['/path2']['put']['responses']); } + /** @test */ + public function adds_responses_correctly_as_array_of_objects() + { + $endpointData1 = $this->createMockEndpointData([ + 'httpMethods' => ['GET'], + 'uri' => '/path1', + 'responses' => [ + [ + 'status' => 200, + 'description' => 'Successfully.', + 'content' => '[{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}]', + ], + ], + ]); + $groups = [$this->createGroup([$endpointData1])]; + + $results = $this->generate($groups); + + $this->assertCount(1, $results['paths']['/path1']['get']['responses']); + $this->assertArraySubset([ + '200' => [ + 'description' => 'Successfully.', + 'content' => [ + 'application/json' => [ + 'schema' => [ + 'type' => 'array', + 'items' => [ + 'type' => 'object', + 'properties' => [ + 'id' => [ + 'type' => 'integer', + 'example' => 1, + ], + 'name' => [ + 'type' => 'string', + 'example' => 'John', + ], + ] + ], + ], + ], + ], + ], + ], $results['paths']['/path1']['get']['responses']); + } + /** @test */ public function adds_required_fields_on_array_of_objects() {