From a030e01011d87b7fda375d0b50f6c1080b187775 Mon Sep 17 00:00:00 2001 From: Cees-Jan Kiewiet Date: Tue, 17 Jan 2023 08:54:50 +0100 Subject: [PATCH] [openapi v3.1] Preserve property item keys This is mainly useful when dealing with webhooks to use the array index as a name for the given webhook as the spec uses it as a unique identifier: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object --- src/SpecBaseObject.php | 12 ++++++------ tests/spec/SchemaTest.php | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/SpecBaseObject.php b/src/SpecBaseObject.php index 4e57a5e..919da7e 100644 --- a/src/SpecBaseObject.php +++ b/src/SpecBaseObject.php @@ -86,22 +86,22 @@ public function __construct(array $data) } else { // array $this->_properties[$property] = []; - foreach ($data[$property] as $item) { + foreach ($data[$property] as $key => $item) { if ($type[0] === Type::STRING) { if (!is_string($item)) { $this->_errors[] = "property '$property' must be array of strings, but array has " . gettype($item) . " element."; } - $this->_properties[$property][] = $item; + $this->_properties[$property][$key] = $item; } elseif (Type::isScalar($type[0])) { - $this->_properties[$property][] = $item; + $this->_properties[$property][$key] = $item; } elseif ($type[0] === Type::ANY) { if (is_array($item) && isset($item['$ref'])) { - $this->_properties[$property][] = new Reference($item, null); + $this->_properties[$property][$key] = new Reference($item, null); } else { - $this->_properties[$property][] = $item; + $this->_properties[$property][$key] = $item; } } else { - $this->_properties[$property][] = $this->instantiate($type[0], $item); + $this->_properties[$property][$key] = $this->instantiate($type[0], $item); } } } diff --git a/tests/spec/SchemaTest.php b/tests/spec/SchemaTest.php index 1600b3b..4c307b2 100644 --- a/tests/spec/SchemaTest.php +++ b/tests/spec/SchemaTest.php @@ -420,4 +420,31 @@ public function testPropertyNameRef() $this->assertEquals('string', $person->properties['name']->type); $this->assertEquals('string', $person->properties['$ref']->type); } + + public function testArrayKeyIsPerseveredInPropertiesThatAreArrays() + { + $json = <<<'JSON' +{ + "webhooks": { + "branch-protection-rule-created": { + "post": { + "description": "A branch protection rule was created.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + } + } + } + } +} +JSON; + $openApi = Reader::readFromJson($json); + self::assertArrayHasKey('branch-protection-rule-created', $openApi->webhooks); + } }