Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce OpenAPI Version to every spec object to allow different type of properties for every openAPI version #9

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions bin/php-openapi
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env php
<?php

use openapiphp\openapi\OpenApiVersion;
use openapiphp\openapi\ReferenceContext;

$composerAutoload = [
Expand Down Expand Up @@ -126,7 +127,7 @@ switch ($command) {

// OpenAPI version check
$openApiVersion = $openApi->getMajorVersion();
if ($openApiVersion === \openapiphp\openapi\spec\OpenApi::VERSION_UNSUPPORTED) {
if ($openApiVersion === OpenApiVersion::VERSION_UNSUPPORTED) {
error("Unsupported OpenAPI version: " . $openApi->openapi);
}

Expand All @@ -135,11 +136,11 @@ switch ($command) {

$validator = new JsonSchema\Validator;
$openApiData = $openApi->getSerializableData();
$validator->validate($openApiData, (object)['$ref' => 'file://' . dirname(__DIR__) . "/schemas/openapi-v{$openApiVersion}.json"]);
$validator->validate($openApiData, (object)['$ref' => 'file://' . dirname(__DIR__) . "/schemas/openapi-v{$openApiVersion->value}.json"]);

if ($validator->isValid() && empty($errors)) {
if(!$silentMode) {
print_formatted("The supplied API Description \B\Gvalidates\C against the OpenAPI v{$openApiVersion} schema.\n", STDERR);
print_formatted("The supplied API Description \B\Gvalidates\C against the OpenAPI v{$openApiVersion->value} schema.\n", STDERR);
}
exit(0);
}
Expand All @@ -162,7 +163,7 @@ switch ($command) {
}
}
if (!$validator->isValid()) {
print_formatted("\BOpenAPI v{$openApiVersion} schema violations:\C\n", STDERR);
print_formatted("\BOpenAPI v{$openApiVersion->value} schema violations:\C\n", STDERR);
$errors = $validator->getErrors();
foreach ($errors as $error) {
// hide some errors triggered by other errors further down the path
Expand Down
7 changes: 6 additions & 1 deletion phpstan-baseline.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,12 @@
'path' => __DIR__ . '/src/spec/PathItem.php',
];
$ignoreErrors[] = [
'message' => '#^Method openapiphp\\\\openapi\\\\spec\\\\Reference\\:\\:resolve\\(\\) should return array\\|openapiphp\\\\openapi\\\\SpecObjectInterface\\|string\\|null but returns mixed\\.$#',
'message' => '#^Access to an undefined property openapiphp\\\\openapi\\\\SpecBaseObject\\:\\:\\$description\\.$#',
'count' => 1,
'path' => __DIR__ . '/src/spec/Reference.php',
];
$ignoreErrors[] = [
'message' => '#^Access to an undefined property openapiphp\\\\openapi\\\\SpecBaseObject\\:\\:\\$summary\\.$#',
'count' => 1,
'path' => __DIR__ . '/src/spec/Reference.php',
];
Expand Down
12 changes: 12 additions & 0 deletions src/OpenApiVersion.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace openapiphp\openapi;

enum OpenApiVersion: string
{
case VERSION_3_0 = '3.0';
case VERSION_3_1 = '3.1';
case VERSION_UNSUPPORTED = 'unsupported';
}
4 changes: 2 additions & 2 deletions src/Reader.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ public static function readFromJson(string $json, string $baseType = OpenApi::cl
/**
* Populate OpenAPI spec object from YAML data.
*
* @param string $yaml the YAML string to decode.
* @param string $baseType the base Type to instantiate. This must be an instance of [[SpecObjectInterface]].
* @param string $yaml the YAML string to decode.
* @param class-string<SpecObjectInterface> $baseType the base Type to instantiate. This must be an instance of [[SpecObjectInterface]].
* The default is [[OpenApi]] which is the base type of a OpenAPI specification file.
* You may choose a different type if you instantiate objects from sub sections of a specification.
* @phpstan-param class-string<T> $baseType
Expand Down
29 changes: 19 additions & 10 deletions src/ReferenceContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,11 @@ class ReferenceContext
*
* @throws UnresolvableReferenceException in case an invalid or non-absolute URI is provided.
*/
public function __construct(private readonly SpecObjectInterface|null $_baseSpec, string $uri, ReferenceContextCache|null $cache = null)
{
public function __construct(
private readonly SpecObjectInterface|null $_baseSpec,
string $uri,
ReferenceContextCache|null $cache = null,
) {
$this->_uri = $this->normalizeUri($uri);
$this->_cache = $cache ?? new ReferenceContextCache();
if ($cache instanceof ReferenceContextCache || ! $this->_baseSpec instanceof SpecObjectInterface) {
Expand Down Expand Up @@ -263,11 +266,16 @@ public function fetchReferencedFile(string $uri): mixed
*
* @return SpecObjectInterface|array<string, mixed>|null
*/
public function resolveReferenceData(string $uri, JsonPointer $pointer, mixed $data, string|null $toType): SpecObjectInterface|array|string|null
{
public function resolveReferenceData(
string $uri,
JsonPointer $pointer,
mixed $data,
ReferenceTarget|null $toType,
OpenApiVersion|null $openApiVersion,
): SpecObjectInterface|array|string|null {
$ref = $uri . '#' . $pointer->getPointer();
if ($this->_cache->has($ref, $toType)) {
return $this->_cache->get($ref, $toType);
if ($this->_cache->has($ref, $toType?->asString())) {
return $this->_cache->get($ref, $toType?->asString());
}

$referencedData = $pointer->evaluate($data);
Expand All @@ -278,13 +286,14 @@ public function resolveReferenceData(string $uri, JsonPointer $pointer, mixed $d

// transitive reference
if (isset($referencedData['$ref'])) {
return new Reference($referencedData, $toType);
return new Reference($referencedData, $openApiVersion, $toType);
}

$referencedObject = $toType !== null ? new $toType($referencedData) : $referencedData;
$referencedObject = $toType?->createInstance($referencedData);
$referencedData = $referencedObject ?? $referencedData;

$this->_cache->set($ref, $toType, $referencedObject);
$this->_cache->set($ref, $toType?->asString(), $referencedData);

return $referencedObject;
return $referencedData;
}
}
62 changes: 62 additions & 0 deletions src/ReferenceTarget.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

declare(strict_types=1);

namespace openapiphp\openapi;

use function array_is_list;
use function array_key_exists;
use function get_class;
use function is_array;
use function is_string;
use function is_subclass_of;

/**
* Add the "parent" Spec with the changed attribute as Reference context
* This will be used to check if the resolved $ref contains only allowed attributes for the object containing the $ref
*/
class ReferenceTarget
{
public function __construct(
public readonly SpecObjectInterface $currentSpec,
public readonly string|null $targetProperty = null,
) {
}

public function asString(): string
{
return get_class($this->currentSpec) . $this->targetProperty;
}

public function createInstance(mixed $data): SpecObjectInterface|null
{
$targetSpec = $this->currentSpec->attributes()[$this->targetProperty] ?? get_class($this->currentSpec);
if (is_string($targetSpec) && is_subclass_of($targetSpec, SpecObjectInterface::class)) {
return new $targetSpec(
is_array($data) ? $data : [],
$this->currentSpec->getApiVersion(),
);
}

return null;
}

public function allowsAttribute(string $attributeName): bool
{
$constructorArgs = (array) $this->currentSpec->getSerializableData();
$constructorArgs = $constructorArgs[$this->targetProperty] ?? $constructorArgs;
$target = $this->createInstance($constructorArgs);

if ($target !== null) {
$targetAttributes = $target->attributes();
// if there aren't any properties defined, every attribute is allowed
if (array_is_list($targetAttributes)) {
return true;
}

return array_key_exists($attributeName, $target->attributes());
}

return false;
}
}
56 changes: 41 additions & 15 deletions src/SpecBaseObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,6 @@
private SpecObjectInterface|null $_baseDocument = null;
private JsonPointer|null $_jsonPointer = null;

/** @return array<string, string|list<string>> array of attributes available in this object. */
abstract protected function attributes(): array;

/**
* Perform validation on this object, check data against OpenAPI Specification rules.
*
Expand All @@ -62,8 +59,10 @@
abstract protected function performValidation(): void;

/** @inheritDoc */
public function __construct(array $data)
{
public function __construct(
array $data,
protected OpenApiVersion|null $openApiVersion = null,
) {
foreach ($this->attributes() as $property => $type) {
if (! isset($data[$property])) {
continue;
Expand All @@ -89,7 +88,11 @@
switch (count($type)) {
case 1:
if (isset($data[$property]['$ref'])) {
$this->_properties[$property] = new Reference($data[$property], null);
$this->_properties[$property] = new Reference(
$data[$property],
$this->openApiVersion,
new ReferenceTarget($this, $property),
);
} else {
// array
$this->_properties[$property] = [];
Expand All @@ -107,10 +110,14 @@
$this->_properties[$property][$key] = $item;
} elseif ($type[0] === Type::ANY) {
$this->_properties[$property][$key] = is_array($item) && isset($item['$ref'])
? new Reference($item, null)
? new Reference(
$item,
$this->openApiVersion,
new ReferenceTarget($this, $property),
)
: $item;
} else {
$this->_properties[$property][$key] = $this->instantiate($type[0], $item);
$this->_properties[$property][$key] = $this->instantiate($type[0], $item, $this->openApiVersion);

Check failure on line 120 in src/SpecBaseObject.php

View workflow job for this annotation

GitHub Actions / Tests with coverage and PR Comments (8.1)

Parameter #1 $type of method openapiphp\openapi\SpecBaseObject::instantiate() expects class-string<openapiphp\openapi\SpecObjectInterface>, string given.
}
}
}
Expand Down Expand Up @@ -139,7 +146,7 @@
} elseif ($type[1] === Type::ANY || Type::isScalar($type[1])) {
$this->_properties[$property][$key] = $item;
} else {
$this->_properties[$property][$key] = $this->instantiate($type[1], $item);
$this->_properties[$property][$key] = $this->instantiate($type[1], $item, $this->openApiVersion);

Check failure on line 149 in src/SpecBaseObject.php

View workflow job for this annotation

GitHub Actions / Tests with coverage and PR Comments (8.1)

Parameter #1 $type of method openapiphp\openapi\SpecBaseObject::instantiate() expects class-string<openapiphp\openapi\SpecObjectInterface>, string given.
}
}

Expand All @@ -149,10 +156,14 @@
$this->_properties[$property] = $data[$property];
} elseif ($type === Type::ANY) {
$this->_properties[$property] = is_array($data[$property]) && isset($data[$property]['$ref'])
? new Reference($data[$property], null)
? new Reference(
$data[$property],
$this->openApiVersion,
new ReferenceTarget($this, $property),
)
: $data[$property];
} else {
$this->_properties[$property] = $this->instantiate($type, $data[$property]);
$this->_properties[$property] = $this->instantiate($type, $data[$property], $this->openApiVersion);

Check failure on line 166 in src/SpecBaseObject.php

View workflow job for this annotation

GitHub Actions / Tests with coverage and PR Comments (8.1)

Parameter #1 $type of method openapiphp\openapi\SpecBaseObject::instantiate() expects class-string<openapiphp\openapi\SpecObjectInterface>, string given.
}

unset($data[$property]);
Expand Down Expand Up @@ -315,15 +326,25 @@
return [];
}

/** @throws TypeErrorException */
protected function instantiate(string $type, mixed $data): object
/**
* @param class-string<SpecObjectInterface> $type
*
* @throws TypeErrorException
*/
protected function instantiate(string $type, mixed $data, OpenApiVersion|null $openApiVersion): object
{
if ($data instanceof $type || $data instanceof Reference) {

Check failure on line 336 in src/SpecBaseObject.php

View workflow job for this annotation

GitHub Actions / Tests with coverage and PR Comments (8.1)

Instanceof between mixed and openapiphp\openapi\spec\Reference will always evaluate to false.
return $data;
}

if (is_array($data) && isset($data['$ref'])) {
return new Reference($data, $type);
return new Reference(
$data,
$openApiVersion,
new ReferenceTarget(
new $type([], $openApiVersion),
),
);
}

if (! is_array($data)) {
Expand All @@ -336,8 +357,8 @@
}

try {
return new $type($data);
return new $type($data, $openApiVersion);
} catch (TypeError $e) {

Check failure on line 361 in src/SpecBaseObject.php

View workflow job for this annotation

GitHub Actions / Tests with coverage and PR Comments (8.1)

Dead catch - TypeError is never thrown in the try block.
throw new TypeErrorException(
sprintf("Unable to instantiate %s Object with data '", $type) . print_r(
$data,
Expand Down Expand Up @@ -628,4 +649,9 @@

return $extensions;
}

public function getApiVersion(): OpenApiVersion
{
return $this->openApiVersion ?? OpenApiVersion::VERSION_UNSUPPORTED;
}
}
7 changes: 6 additions & 1 deletion src/SpecObjectInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ interface SpecObjectInterface
*
* @throws TypeErrorException in case invalid data is supplied.
*/
public function __construct(array $data);
public function __construct(array $data, OpenApiVersion|null $openApiVersion = null);

public function getApiVersion(): OpenApiVersion;

/** @return array<array-key, string|list<string>> array of attributes available in this object. */
public function attributes(): array;

/**
* @return object returns the serializable data of this object for converting it
Expand Down
18 changes: 16 additions & 2 deletions src/spec/Callback.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use openapiphp\openapi\DocumentContextInterface;
use openapiphp\openapi\exceptions\UnresolvableReferenceException;
use openapiphp\openapi\json\JsonPointer;
use openapiphp\openapi\OpenApiVersion;
use openapiphp\openapi\ReferenceContext;
use openapiphp\openapi\SpecObjectInterface;

Expand All @@ -31,7 +32,7 @@ class Callback implements SpecObjectInterface, DocumentContextInterface
private JsonPointer|null $_jsonPointer = null;

/** @inheritDoc */
public function __construct(array $data)
public function __construct(array $data, private readonly OpenApiVersion|null $openApiVersion = null)
{
if (count($data) !== 1) {
$this->_errors[] = 'Callback object must have exactly one URL.';
Expand All @@ -40,7 +41,7 @@ public function __construct(array $data)
}

$this->_url = key($data);
$this->_pathItem = new PathItem($data[$this->_url]);
$this->_pathItem = new PathItem($data[$this->_url], $this->openApiVersion);
}

/**
Expand Down Expand Up @@ -156,4 +157,17 @@ public function getDocumentPosition(): JsonPointer|null
{
return $this->_jsonPointer;
}

public function getApiVersion(): OpenApiVersion
{
return $this->openApiVersion ?? OpenApiVersion::VERSION_UNSUPPORTED;
}

/** @inheritDoc */
public function attributes(): array
{
return [
[Type::STRING, PathItem::class],
];
}
}
2 changes: 1 addition & 1 deletion src/spec/Components.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
final class Components extends SpecBaseObject
{
/** @inheritDoc */
protected function attributes(): array
public function attributes(): array
{
return [
'callbacks' => [Type::STRING, Callback::class],
Expand Down
2 changes: 1 addition & 1 deletion src/spec/Contact.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
class Contact extends SpecBaseObject
{
/** @inheritDoc */
protected function attributes(): array
public function attributes(): array
{
return [
'name' => Type::STRING,
Expand Down
Loading
Loading