|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the NelmioApiDocBundle package. |
| 7 | + * |
| 8 | + * (c) Nelmio |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view the LICENSE |
| 11 | + * file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Nelmio\ApiDocBundle\TypeDescriber; |
| 15 | + |
| 16 | +use Nelmio\ApiDocBundle\Describer\ModelRegistryAwareInterface; |
| 17 | +use Nelmio\ApiDocBundle\Describer\ModelRegistryAwareTrait; |
| 18 | +use Nelmio\ApiDocBundle\Model\Model; |
| 19 | +use OpenApi\Annotations\Schema; |
| 20 | +use phpDocumentor\Reflection\DocBlock\Tags\Template; |
| 21 | +use phpDocumentor\Reflection\DocBlockFactory; |
| 22 | +use phpDocumentor\Reflection\DocBlockFactoryInterface; |
| 23 | +use Symfony\Component\PropertyInfo\Type as LegacyType; |
| 24 | +use Symfony\Component\TypeInfo\Type; |
| 25 | +use Symfony\Component\TypeInfo\Type\GenericType; |
| 26 | +use Symfony\Component\TypeInfo\Type\ObjectType; |
| 27 | + |
| 28 | +/** |
| 29 | + * @implements TypeDescriberInterface<GenericType> |
| 30 | + * |
| 31 | + * @internal |
| 32 | + */ |
| 33 | +final class GenericClassDescriber implements TypeDescriberInterface, ModelRegistryAwareInterface |
| 34 | +{ |
| 35 | + use ModelRegistryAwareTrait; |
| 36 | + |
| 37 | + private DocBlockFactoryInterface $docBlockFactory; |
| 38 | + |
| 39 | + public function __construct() |
| 40 | + { |
| 41 | + $this->docBlockFactory = DocBlockFactory::createInstance(); |
| 42 | + } |
| 43 | + |
| 44 | + public function describe(Type $type, Schema $schema, array $context = []): void |
| 45 | + { |
| 46 | + $wrappedType = $type->getWrappedType(); |
| 47 | + $reflectionClass = new \ReflectionClass($wrappedType->getClassName()); |
| 48 | + |
| 49 | + if (false !== $reflectionClass->getDocComment()) { |
| 50 | + /** @var Template[] $templateTags */ |
| 51 | + $templateTags = $this->docBlockFactory |
| 52 | + ->create($reflectionClass) |
| 53 | + ->getTagsByName('template'); |
| 54 | + $templateNames = array_map( |
| 55 | + static fn (Template $template): string => $template->getTemplateName(), |
| 56 | + $templateTags, |
| 57 | + ); |
| 58 | + |
| 59 | + if ([] !== $templateNames) { |
| 60 | + $context[TemplateDescriber::TEMPLATES_KEY] = array_combine($templateNames, $type->getVariableTypes()); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + $schema->ref = $this->modelRegistry->register( |
| 65 | + new Model(new LegacyType('object', false, $wrappedType->getClassName()), serializationContext: $context) |
| 66 | + ); |
| 67 | + } |
| 68 | + |
| 69 | + public function supports(Type $type, array $context = []): bool |
| 70 | + { |
| 71 | + return $type instanceof GenericType |
| 72 | + && $type->getWrappedType() instanceof ObjectType; |
| 73 | + } |
| 74 | +} |
0 commit comments