Skip to content

Commit

Permalink
Added basic information about current OpenAPI version
Browse files Browse the repository at this point in the history
  • Loading branch information
cebe committed Oct 18, 2021
1 parent 859071c commit 69c07ef
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/spec/OpenApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@
*/
class OpenApi extends SpecBaseObject
{
const VERSION_3_0 = '3.0.x';
const VERSION_3_1 = '3.1.x';
const VERSION_UNSUPPORTED = 'unsupported';

/**
* Pattern used to validate OpenAPI versions.
*/
const PATTERN_VERSION = '/^(3\.(0|1))\.\d+(-rc\d)?$/i';

/**
* @return array array of attributes available in this object.
*/
Expand Down Expand Up @@ -75,8 +84,31 @@ public function __get($name)
public function performValidation()
{
$this->requireProperties(['openapi', 'info', 'paths']);
if (!empty($this->openapi) && !preg_match('/^3\.0\.\d+(-rc\d)?$/i', $this->openapi)) {
if (!empty($this->openapi) && !preg_match(static::PATTERN_VERSION, $this->openapi)) {
$this->addError('Unsupported openapi version: ' . $this->openapi);
}
}

/**
* Returns the OpenAPI major version of the loaded OpenAPI description.
* @return string This returns a value of one of the `VERSION_*`-constants. Currently supported versions are:
*
* - `VERSION_3_0 = '3.0.x'`
* - `VERSION_3_1 = '3.1.x'`
*
* For unsupported version, this function will return `VERSION_UNSUPPORTED = 'unsupported'`
*/
public function getMajorVersion()
{
if (preg_match(static::PATTERN_VERSION, $this->openapi, $matches)) {
switch ($matches[1]) {
case '3.0':
return static::VERSION_3_0;
case '3.1':
return static::VERSION_3_1;
}
}

return self::VERSION_UNSUPPORTED;
}
}
28 changes: 28 additions & 0 deletions tests/spec/OpenApiTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

use cebe\openapi\spec\OpenApi;
use cebe\openapi\Reader;
use Symfony\Component\Yaml\Yaml;

/**
Expand Down Expand Up @@ -248,4 +249,31 @@ public function testSpecs($openApiFile)
}

}

public function testVersions()
{
$yaml = <<<YAML
openapi: 3.0.2
info:
title: Test API
version: 1
paths: []
YAML;
$openapi = Reader::readFromYaml($yaml);
$this->assertTrue($openapi->validate(), print_r($openapi->getErrors(), true));
$this->assertEquals('3.0.x', $openapi->getMajorVersion());

$yaml = <<<YAML
openapi: 3.1.0
info:
title: Test API
version: 1
paths: []
YAML;
$openapi = Reader::readFromYaml($yaml);
$this->assertTrue($openapi->validate(), print_r($openapi->getErrors(), true));
$this->assertEquals('3.1.x', $openapi->getMajorVersion());


}
}

0 comments on commit 69c07ef

Please sign in to comment.