From e6ba5d6d69d85bb48a1f6ce8419a71283fe11e60 Mon Sep 17 00:00:00 2001 From: Corey Mcmahon Date: Wed, 16 Oct 2024 20:15:13 +1100 Subject: [PATCH] Add `enum` list to Open API spec response properties --- src/Writing/OpenAPISpecWriter.php | 5 ++++ tests/Unit/OpenAPISpecWriterTest.php | 39 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/Writing/OpenAPISpecWriter.php b/src/Writing/OpenAPISpecWriter.php index 52708b2a..bbc4fb22 100644 --- a/src/Writing/OpenAPISpecWriter.php +++ b/src/Writing/OpenAPISpecWriter.php @@ -609,6 +609,11 @@ public function generateSchemaForValue(mixed $value, OutputEndpointData $endpoin ]; $this->setDescription($schema, $endpoint, $path); + // Set enum values for the property if they exist + if (isset($endpoint->responseFields[$path]->enumValues)) { + $schema['enum'] = $endpoint->responseFields[$path]->enumValues; + } + if ($schema['type'] === 'array' && !empty($value)) { $schema['example'] = json_decode(json_encode($schema['example']), true); // Convert stdClass to array diff --git a/tests/Unit/OpenAPISpecWriterTest.php b/tests/Unit/OpenAPISpecWriterTest.php index 019415c8..3f5cd67c 100644 --- a/tests/Unit/OpenAPISpecWriterTest.php +++ b/tests/Unit/OpenAPISpecWriterTest.php @@ -744,6 +744,45 @@ public function adds_more_than_two_answers_correctly_using_oneOf() ], $results['paths']['/path1']['post']['responses']); } + /** @test */ + public function adds_enum_values_to_response_properties() + { + $endpointData = $this->createMockEndpointData([ + 'uri' => '/path', + 'httpMethods' => ['POST'], + 'responses' => [ + [ + 'status' => 200, + 'description' => 'This one', + 'content' => '{"status": "one"}', + ], + ], + 'responseFields' => [ + 'status' => ['enumValues' => ['one', 'two', 'three']], + ], + ]); + + $groups = [$this->createGroup([$endpointData])]; + + $results = $this->generate($groups); + + $this->assertArraySubset([ + '200' => [ + 'content' => [ + 'application/json' => [ + 'schema' => [ + 'properties' => [ + 'status' => [ + 'enum' => ['one', 'two', 'three'], + ], + ], + ], + ], + ], + ], + ], $results['paths']['/path']['post']['responses']); + } + protected function createMockEndpointData(array $custom = []): OutputEndpointData { $faker = Factory::create();