Skip to content

Commit 69c07ef

Browse files
committed
Added basic information about current OpenAPI version
1 parent 859071c commit 69c07ef

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

src/spec/OpenApi.php

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,15 @@
2727
*/
2828
class OpenApi extends SpecBaseObject
2929
{
30+
const VERSION_3_0 = '3.0.x';
31+
const VERSION_3_1 = '3.1.x';
32+
const VERSION_UNSUPPORTED = 'unsupported';
33+
34+
/**
35+
* Pattern used to validate OpenAPI versions.
36+
*/
37+
const PATTERN_VERSION = '/^(3\.(0|1))\.\d+(-rc\d)?$/i';
38+
3039
/**
3140
* @return array array of attributes available in this object.
3241
*/
@@ -75,8 +84,31 @@ public function __get($name)
7584
public function performValidation()
7685
{
7786
$this->requireProperties(['openapi', 'info', 'paths']);
78-
if (!empty($this->openapi) && !preg_match('/^3\.0\.\d+(-rc\d)?$/i', $this->openapi)) {
87+
if (!empty($this->openapi) && !preg_match(static::PATTERN_VERSION, $this->openapi)) {
7988
$this->addError('Unsupported openapi version: ' . $this->openapi);
8089
}
8190
}
91+
92+
/**
93+
* Returns the OpenAPI major version of the loaded OpenAPI description.
94+
* @return string This returns a value of one of the `VERSION_*`-constants. Currently supported versions are:
95+
*
96+
* - `VERSION_3_0 = '3.0.x'`
97+
* - `VERSION_3_1 = '3.1.x'`
98+
*
99+
* For unsupported version, this function will return `VERSION_UNSUPPORTED = 'unsupported'`
100+
*/
101+
public function getMajorVersion()
102+
{
103+
if (preg_match(static::PATTERN_VERSION, $this->openapi, $matches)) {
104+
switch ($matches[1]) {
105+
case '3.0':
106+
return static::VERSION_3_0;
107+
case '3.1':
108+
return static::VERSION_3_1;
109+
}
110+
}
111+
112+
return self::VERSION_UNSUPPORTED;
113+
}
82114
}

tests/spec/OpenApiTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php
22

33
use cebe\openapi\spec\OpenApi;
4+
use cebe\openapi\Reader;
45
use Symfony\Component\Yaml\Yaml;
56

67
/**
@@ -248,4 +249,31 @@ public function testSpecs($openApiFile)
248249
}
249250

250251
}
252+
253+
public function testVersions()
254+
{
255+
$yaml = <<<YAML
256+
openapi: 3.0.2
257+
info:
258+
title: Test API
259+
version: 1
260+
paths: []
261+
YAML;
262+
$openapi = Reader::readFromYaml($yaml);
263+
$this->assertTrue($openapi->validate(), print_r($openapi->getErrors(), true));
264+
$this->assertEquals('3.0.x', $openapi->getMajorVersion());
265+
266+
$yaml = <<<YAML
267+
openapi: 3.1.0
268+
info:
269+
title: Test API
270+
version: 1
271+
paths: []
272+
YAML;
273+
$openapi = Reader::readFromYaml($yaml);
274+
$this->assertTrue($openapi->validate(), print_r($openapi->getErrors(), true));
275+
$this->assertEquals('3.1.x', $openapi->getMajorVersion());
276+
277+
278+
}
251279
}

0 commit comments

Comments
 (0)