diff --git a/src/SpecBaseObject.php b/src/SpecBaseObject.php index 1de429b..5bac350 100644 --- a/src/SpecBaseObject.php +++ b/src/SpecBaseObject.php @@ -525,4 +525,37 @@ public function getExtensions(): array } return $extensions; } + + /** + * Returns extension property with `x-` prefix. + * @see https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#specificationExtensions + * @param string $key The property key, e.g. 'x-prop' or 'prop' (the 'x-' prefix is added automatically if needed). + * @return mixed|null The property value, if present. + * @since 1.8.0 + */ + public function getExtension(string $key) + { + if (strpos($key, 'x-') !== 0) { + $key = 'x-' . $key; + } + + return $this->_properties[$key] ?? null; + } + + /** + * Set extension property with `x-` prefix. + * @see https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#specificationExtensions + * @param string $key The property key, e.g. 'x-prop' or 'prop' (the 'x-' prefix is added automatically if needed). + * @param mixed $value The property value. + * @return void + * @since 1.8.0 + */ + public function setExtension(string $key, $value): void + { + if (strpos($key, 'x-') !== 0) { + $key = 'x-' . $key; + } + + $this->_properties[$key] = $value; + } } diff --git a/tests/WriterTest.php b/tests/WriterTest.php index fc415b5..4be35fd 100644 --- a/tests/WriterTest.php +++ b/tests/WriterTest.php @@ -37,6 +37,33 @@ public function testWriteJson() ); } + public function testWriteJsonExtensions() + { + $openapi = $this->createOpenAPI(); + $openapi->{'x-extra-var'} = 'foo'; + $openapi->setExtension('x-another-var', 'bar'); + $openapi->setExtension('short-var', 'baz'); + + $json = \cebe\openapi\Writer::writeToJson($openapi); + + $this->assertEquals(preg_replace('~\R~', "\n", <<createOpenAPI(); diff --git a/tests/spec/InfoTest.php b/tests/spec/InfoTest.php index 932e5e0..35f8204 100644 --- a/tests/spec/InfoTest.php +++ b/tests/spec/InfoTest.php @@ -27,6 +27,7 @@ public function testRead() name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html version: 1.0.1 +x-extra-var: foo YAML , Info::class); @@ -46,6 +47,11 @@ public function testRead() $this->assertInstanceOf(License::class, $info->license); $this->assertEquals('Apache 2.0', $info->license->name); $this->assertEquals('https://www.apache.org/licenses/LICENSE-2.0.html', $info->license->url); + + $this->assertEquals('foo', $info->getExtensions()['x-extra-var']); + $this->assertEquals('foo', $info->getExtension('x-extra-var')); + $this->assertEquals('foo', $info->getExtension('extra-var')); + $this->assertNull($info->getExtension('another-var')); } public function testReadInvalid() @@ -117,4 +123,4 @@ public function testReadInvalidLicense() $this->assertNull($info->contact); } -} \ No newline at end of file +}