Skip to content

Commit

Permalink
Move Reflection handling into own Reader
Browse files Browse the repository at this point in the history
This allows to fetch default values via reflection should they so far
not have been set via other means.

As that happens before the SymfonyConstraint handling, the required
fields should be set as expected but should also take into account the
default values set via Attributes or Annotations.
  • Loading branch information
heiglandreas committed Nov 7, 2024
1 parent 0a81850 commit 7a499cb
Show file tree
Hide file tree
Showing 3 changed files with 162 additions and 33 deletions.
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($annotationsReader);
}

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
158 changes: 158 additions & 0 deletions src/ModelDescriber/Annotations/ReflectionReader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
<?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 Doctrine\Common\Annotations\Reader;
use Nelmio\ApiDocBundle\OpenApiPhp\Util;
use Nelmio\ApiDocBundle\Util\SetsContextTrait;
use OpenApi\Annotations as OA;
use OpenApi\Context;
use OpenApi\Generator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints as Assert;

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

private ?Reader $annotationsReader;

/**
* @var OA\Schema
*/
private $schema;

public function __construct(?Reader $annotationsReader)
{
$this->annotationsReader = $annotationsReader;
}

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

$serializedName = $reflection->getName();
foreach (['', 'get', 'is', 'has', 'can', 'add', 'remove', 'set'] as $prefix) {
if (str_starts_with($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;
}

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

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

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

private function getDefaultFromMethodReflection(\ReflectionMethod $reflection): mixed
{
if (! str_starts_with('set', $reflection->name)) {
return Generator::UNDEFINED;
}

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

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

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

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

return $param->getDefaultValue();
}

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

$reflectionProp = $reflection->getDeclaringClass()->getProperty($propertyName);
if (! $reflectionProp->hasDefaultValue()) {
return Generator::UNDEFINED;
}

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

return $reflectionProp->getDefaultValue();
}
}
33 changes: 0 additions & 33 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 @@ -168,22 +151,6 @@ public function describe(Model $model, OA\Schema $schema)
continue;
}

if (Generator::UNDEFINED === $property->default && array_key_exists($propertyName, $defaultValues)) {
$property->default = $defaultValues[$propertyName];
}

if (Generator::UNDEFINED !== $property->default) {
// Fix for https://github.com/nelmio/NelmioApiDocBundle/issues/2222
// When a default value has been set for the property, we can
// remove the field from the required fields.
if (is_array($schema->required) && ($key = array_search($propertyName, $schema->required, true)) !== false) {
unset($schema->required[$key]);
}
}
if ([] === $schema->required) {
$schema->required = Generator::UNDEFINED;
}

$types = $this->propertyInfo->getTypes($class, $propertyName);
if (null === $types || 0 === count($types)) {
throw new \LogicException(sprintf('The PropertyInfo component was not able to guess the type of %s::$%s. You may need to add a `@var` annotation or use `@OA\Property(type="")` to make its type explicit.', $class, $propertyName));
Expand Down

0 comments on commit 7a499cb

Please sign in to comment.