Skip to content

Commit

Permalink
Removed error catching on invalid attributes
Browse files Browse the repository at this point in the history
The error catching made it hard to find the reason for "ignored" attributes. This change addresses the issues zircote#1267 and zircote#1162.

Instead of catching errors of non existing attribute classes, the existence of the class is checked before the attribute is tried to instantiate. This reveals invalid attribute definitions, but there won't be shown errors for attributes whose class definitions do not exist.
  • Loading branch information
stollr committed Mar 21, 2023
1 parent 4a1d127 commit 3b62bed
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/Analysers/AttributeAnnotationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ public function build(\Reflector $reflector, Context $context): array
$annotations = [];
try {
foreach ($reflector->getAttributes() as $attribute) {
try {
if (class_exists($attribute->getName())) {
$instance = $attribute->newInstance();
if ($instance instanceof OA\AbstractAnnotation) {
$annotations[] = $instance;
}
} catch (\Error $e) {
$context->logger->debug('Could not instantiate attribute: ' . $e->getMessage(), ['exception' => $e]);
} else {
$context->logger->debug(sprintf('Could not instantiate attribute "%s", because class not found.', $attribute->getName()));
}
}

Expand Down
12 changes: 12 additions & 0 deletions tests/Analysers/AttributeAnnotationFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

use OpenApi\Analysers\AttributeAnnotationFactory;
use OpenApi\Tests\Fixtures\UsingAttributes;
use OpenApi\Tests\Fixtures\InvalidPropertyAttribute;
use OpenApi\Tests\OpenApiTestCase;

/**
Expand All @@ -22,4 +23,15 @@ public function testReturnedAnnotationsCout(): void
$annotations = (new AttributeAnnotationFactory())->build($rc, $this->getContext());
$this->assertCount(1, $annotations);
}

public function testErrorOnInvalidAttribute(): void
{
$instance = new InvalidPropertyAttribute();
$rm = new \ReflectionMethod($instance, 'post');

$this->expectException(\TypeError::class);
$this->expectExceptionMessage('OpenApi\Attributes\Property::__construct(): Argument #8 ($required) must be of type ?array, bool given');

(new AttributeAnnotationFactory())->build($rm, $this->getContext());
}
}
17 changes: 17 additions & 0 deletions tests/Fixtures/InvalidPropertyAttribute.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php declare(strict_types=1);

/**
* @license Apache 2.0
*/

namespace OpenApi\Tests\Fixtures;

use OpenApi\Attributes as OA;

class InvalidPropertyAttribute
{
#[OA\Property(required: true)] // required has to be array or null
public function post()
{
}
}

0 comments on commit 3b62bed

Please sign in to comment.