Skip to content

Commit

Permalink
[openapi v3.1] Preserve property item keys
Browse files Browse the repository at this point in the history
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
  • Loading branch information
WyriHaximus committed Mar 23, 2023
1 parent 684aac0 commit a030e01
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/SpecBaseObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
Expand Down
27 changes: 27 additions & 0 deletions tests/spec/SchemaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit a030e01

Please sign in to comment.