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

fix: override code based defaults with explicit ones #2377

Merged
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
4 changes: 4 additions & 0 deletions src/ModelDescriber/Annotations/AnnotationsReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class AnnotationsReader
private PropertyPhpDocReader $phpDocReader;
private OpenApiAnnotationsReader $openApiAnnotationsReader;
private SymfonyConstraintAnnotationReader $symfonyConstraintAnnotationReader;
private ReflectionReader $reflectionReader;

/**
* @param string[] $mediaTypes
Expand All @@ -40,12 +41,14 @@ public function __construct(
$annotationsReader,
$useValidationGroups
);
$this->reflectionReader = new ReflectionReader();
}

public function updateDefinition(\ReflectionClass $reflectionClass, OA\Schema $schema): bool
{
$this->openApiAnnotationsReader->updateSchema($reflectionClass, $schema);
$this->symfonyConstraintAnnotationReader->setSchema($schema);
$this->reflectionReader->setSchema($schema);

return $this->shouldDescribeModelProperties($schema);
}
Expand All @@ -66,6 +69,7 @@ public function updateProperty($reflection, OA\Property $property, ?array $seria
{
$this->openApiAnnotationsReader->updateProperty($reflection, $property, $serializationGroups);
$this->phpDocReader->updateProperty($reflection, $property);
$this->reflectionReader->updateProperty($reflection, $property);
$this->symfonyConstraintAnnotationReader->updateProperty($reflection, $property, $serializationGroups);
}

Expand Down
145 changes: 145 additions & 0 deletions src/ModelDescriber/Annotations/ReflectionReader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<?php

/*
* This file is part of the NelmioApiDocBundle package.
*
* (c) Nelmio
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Nelmio\ApiDocBundle\ModelDescriber\Annotations;

use Nelmio\ApiDocBundle\Util\SetsContextTrait;
use OpenApi\Annotations as OA;
use OpenApi\Generator;

/**
* Read default values of a property from the function or property signature.
*
* This needs to be called before the {@see SymfonyConstraintAnnotationReader},
* otherwise required properties might be considered wrongly.
*
* @internal
*/
final class ReflectionReader
{
use SetsContextTrait;

private ?OA\Schema $schema;

/**
* Update the given property and schema with defined Symfony constraints.
*
* @param \ReflectionProperty|\ReflectionMethod $reflection
*/
public function updateProperty(
$reflection,
OA\Property $property
): void {
// The default has been set by an Annotation or Attribute
// We leave that as it is!
if (Generator::UNDEFINED !== $property->default) {
return;
}

$serializedName = $reflection->getName();
foreach (['get', 'is', 'has', 'can', 'add', 'remove', 'set'] as $prefix) {
if (0 === strpos($serializedName, $prefix)) {
$serializedName = substr($serializedName, strlen($prefix));
}
}

if ($reflection instanceof \ReflectionMethod) {
$methodDefault = $this->getDefaultFromMethodReflection($reflection);
if (Generator::UNDEFINED !== $methodDefault) {
$property->default = $methodDefault;

return;
}
}

if ($reflection instanceof \ReflectionProperty) {
$methodDefault = $this->getDefaultFromPropertyReflection($reflection);
if (Generator::UNDEFINED !== $methodDefault) {
$property->default = $methodDefault;

return;
}
}
// Fix for https://github.com/nelmio/NelmioApiDocBundle/issues/2222
// Promoted properties with a value initialized by the constructor are not considered to have a default value
// and are therefore not returned by ReflectionClass::getDefaultProperties(); see https://bugs.php.net/bug.php?id=81386
$reflClassConstructor = $reflection->getDeclaringClass()->getConstructor();
$reflClassConstructorParameters = null !== $reflClassConstructor ? $reflClassConstructor->getParameters() : [];
foreach ($reflClassConstructorParameters as $parameter) {
if ($parameter->name !== $serializedName) {
continue;
}
if (!$parameter->isDefaultValueAvailable()) {
continue;
}

if (null === $this->schema) {
continue;

Check warning on line 85 in src/ModelDescriber/Annotations/ReflectionReader.php

View check run for this annotation

Codecov / codecov/patch

src/ModelDescriber/Annotations/ReflectionReader.php#L85

Added line #L85 was not covered by tests
}

if (!Generator::isDefault($property->default)) {
continue;

Check warning on line 89 in src/ModelDescriber/Annotations/ReflectionReader.php

View check run for this annotation

Codecov / codecov/patch

src/ModelDescriber/Annotations/ReflectionReader.php#L89

Added line #L89 was not covered by tests
}

$property->default = $parameter->getDefaultValue();
}
}

public function setSchema(OA\Schema $schema): void
{
$this->schema = $schema;
}

/**
* @return mixed|string
*/
private function getDefaultFromMethodReflection(\ReflectionMethod $reflection)
{
if (0 !== strpos($reflection->name, 'set')) {
return Generator::UNDEFINED;
}

if (1 !== $reflection->getNumberOfParameters()) {
return Generator::UNDEFINED;

Check warning on line 111 in src/ModelDescriber/Annotations/ReflectionReader.php

View check run for this annotation

Codecov / codecov/patch

src/ModelDescriber/Annotations/ReflectionReader.php#L111

Added line #L111 was not covered by tests
}

$param = $reflection->getParameters()[0];

if (!$param->isDefaultValueAvailable()) {
return Generator::UNDEFINED;
}

if (null === $param->getDefaultValue()) {
return Generator::UNDEFINED;
}

return $param->getDefaultValue();
}

/**
* @return mixed|string
*/
public function getDefaultFromPropertyReflection(\ReflectionProperty $reflection)
{
$propertyName = $reflection->name;
if (!$reflection->getDeclaringClass()->hasProperty($propertyName)) {
return Generator::UNDEFINED;

Check warning on line 134 in src/ModelDescriber/Annotations/ReflectionReader.php

View check run for this annotation

Codecov / codecov/patch

src/ModelDescriber/Annotations/ReflectionReader.php#L134

Added line #L134 was not covered by tests
}

$defaultValue = $reflection->getDeclaringClass()->getDefaultProperties()[$propertyName] ?? null;

if (null === $defaultValue) {
return Generator::UNDEFINED;
}

return $defaultValue;
}
}
24 changes: 0 additions & 24 deletions src/ModelDescriber/ObjectModelDescriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,23 +125,6 @@ public function describe(Model $model, OA\Schema $schema)
// The SerializerExtractor does expose private/protected properties for some reason, so we eliminate them here
$propertyInfoProperties = array_intersect($propertyInfoProperties, $this->propertyInfo->getProperties($class, []) ?? []);

$defaultValues = array_filter($reflClass->getDefaultProperties(), static function ($value) {
return null !== $value;
});

// Fix for https://github.com/nelmio/NelmioApiDocBundle/issues/2222
// Promoted properties with a value initialized by the constructor are not considered to have a default value
// and are therefore not returned by ReflectionClass::getDefaultProperties(); see https://bugs.php.net/bug.php?id=81386
$reflClassConstructor = $reflClass->getConstructor();
$reflClassConstructorParameters = null !== $reflClassConstructor ? $reflClassConstructor->getParameters() : [];
foreach ($reflClassConstructorParameters as $parameter) {
if (!$parameter->isDefaultValueAvailable()) {
continue;
}

$defaultValues[$parameter->name] = $parameter->getDefaultValue();
}

foreach ($propertyInfoProperties as $propertyName) {
$serializedName = null !== $this->nameConverter ? $this->nameConverter->normalize($propertyName, $class, null, $model->getSerializationContext()) : $propertyName;

Expand All @@ -154,13 +137,6 @@ public function describe(Model $model, OA\Schema $schema)

$property = Util::getProperty($schema, $serializedName);

// Fix for https://github.com/nelmio/NelmioApiDocBundle/issues/2222
// Property default value has to be set before SymfonyConstraintAnnotationReader::processPropertyAnnotations()
// is called to prevent wrongly detected required properties
if (Generator::UNDEFINED === $property->default && array_key_exists($propertyName, $defaultValues)) {
$property->default = $defaultValues[$propertyName];
}

// Interpret additional options
$groups = $model->getGroups();
if (isset($groups[$propertyName]) && is_array($groups[$propertyName])) {
Expand Down
1 change: 1 addition & 0 deletions tests/Functional/FunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ public function testUserModel(): void
'$ref' => '#/components/schemas/User',
],
'type' => 'array',
'default' => [],
],
'dummy' => [
'$ref' => '#/components/schemas/Dummy2',
Expand Down
2 changes: 1 addition & 1 deletion tests/Functional/JMSFunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -328,9 +328,9 @@ public function testNamingStrategyWithConstraints(): void
'type' => 'string',
'maxLength' => 10,
'minLength' => 3,
'default' => 'default'
],
],
'required' => ['beautifulName'],
'schema' => 'JMSNamingStrategyConstraints',
], json_decode($this->getModel('JMSNamingStrategyConstraints')->toJson(), true));
}
Expand Down
Loading