diff --git a/src/Writing/OpenAPISpecWriter.php b/src/Writing/OpenAPISpecWriter.php index 0356f5e0..41e1fb46 100644 --- a/src/Writing/OpenAPISpecWriter.php +++ b/src/Writing/OpenAPISpecWriter.php @@ -635,6 +635,11 @@ public function generateSchemaForValue(mixed $value, OutputEndpointData $endpoin $schema['items']['properties'] = collect($sample)->mapWithKeys(function ($v, $k) use ($endpoint, $path) { return [$k => $this->generateSchemaForValue($v, $endpoint, "$path.$k")]; })->toArray(); + + $required = $this->filterRequiredFields($endpoint, array_keys($schema['items']['properties']), $path); + if ($required) { + $schema['required'] = $required; + } } } diff --git a/tests/Unit/OpenAPISpecWriterTest.php b/tests/Unit/OpenAPISpecWriterTest.php index ec338569..98135c86 100644 --- a/tests/Unit/OpenAPISpecWriterTest.php +++ b/tests/Unit/OpenAPISpecWriterTest.php @@ -598,6 +598,92 @@ public function adds_responses_correctly_as_responses_on_operation_object() ], $results['paths']['/path2']['put']['responses']); } + /** @test */ + public function adds_required_fields_on_objects_wrapped_in_array() + { + $endpointData = $this->createMockEndpointData([ + 'httpMethods' => ['GEt'], + 'uri' => '/path1', + 'responses' => [ + [ + 'status' => 200, + 'description' => 'List of entities', + 'content' => '{"data":[{"name":"Resource name","uuid":"UUID","primary":true}]}', + ], + ], + 'responseFields' => [ + 'data' => [ + 'name' => 'data', + 'type' => 'array', + 'description' => 'Data wrapper', + ], + 'data.name' => [ + 'name' => 'Resource name', + 'type' => 'string', + 'description' => 'Name of the resource object', + 'required' => true, + ], + 'data.uuid' => [ + 'name' => 'Resource UUID', + 'type' => 'string', + 'description' => 'Unique ID for the resource', + 'required' => true, + ], + 'data.primary' => [ + 'name' => 'Is primary', + 'type' => 'bool', + 'description' => 'Is primary resource', + 'required' => true, + ], + ], + ]); + + $groups = [$this->createGroup([$endpointData])]; + + $results = $this->generate($groups); + + $this->assertArraySubset([ + '200' => [ + 'description' => 'List of entities', + 'content' => [ + 'application/json' => [ + 'schema' => [ + 'type' => 'object', + 'properties' => [ + 'data' => [ + 'type' => 'array', + 'description' => 'Data wrapper', + 'items' => [ + 'type' => 'object', + 'properties' => [ + 'name' => [ + 'type' => 'string', + 'description' => 'Name of the resource object', + ], + 'uuid' => [ + 'type' => 'string', + 'description' => 'Unique ID for the resource', + ], + 'primary' => [ + 'type' => 'boolean', + 'description' => 'Is primary resource', + ], + ], + ], + 'required' => [ + 'name', + 'uuid', + 'primary', + ] + ], + ], + ], + ], + ], + ], + ], $results['paths']['/path1']['get']['responses']); + } + /** @test */ public function adds_multiple_responses_correctly_using_oneOf() {