vendor/nelmio/api-doc-bundle/ModelDescriber/ObjectModelDescriber.php line 49

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the NelmioApiDocBundle package.
  4. *
  5. * (c) Nelmio
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Nelmio\ApiDocBundle\ModelDescriber;
  11. use Doctrine\Common\Annotations\Reader;
  12. use Nelmio\ApiDocBundle\Describer\ModelRegistryAwareInterface;
  13. use Nelmio\ApiDocBundle\Describer\ModelRegistryAwareTrait;
  14. use Nelmio\ApiDocBundle\Exception\UndocumentedArrayItemsException;
  15. use Nelmio\ApiDocBundle\Model\Model;
  16. use Nelmio\ApiDocBundle\ModelDescriber\Annotations\AnnotationsReader;
  17. use Nelmio\ApiDocBundle\OpenApiPhp\Util;
  18. use Nelmio\ApiDocBundle\PropertyDescriber\PropertyDescriberInterface;
  19. use OpenApi\Annotations as OA;
  20. use OpenApi\Generator;
  21. use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
  22. use Symfony\Component\PropertyInfo\Type;
  23. use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
  24. use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
  25. class ObjectModelDescriber implements ModelDescriberInterface, ModelRegistryAwareInterface
  26. {
  27. use ModelRegistryAwareTrait;
  28. use ApplyOpenApiDiscriminatorTrait;
  29. /** @var PropertyInfoExtractorInterface */
  30. private $propertyInfo;
  31. /** @var ClassMetadataFactoryInterface|null */
  32. private $classMetadataFactory;
  33. /** @var Reader */
  34. private $doctrineReader;
  35. /** @var PropertyDescriberInterface[] */
  36. private $propertyDescribers;
  37. /** @var string[] */
  38. private $mediaTypes;
  39. /** @var NameConverterInterface|null */
  40. private $nameConverter;
  41. /** @var bool */
  42. private $useValidationGroups;
  43. public function __construct(
  44. PropertyInfoExtractorInterface $propertyInfo,
  45. Reader $reader,
  46. iterable $propertyDescribers,
  47. array $mediaTypes,
  48. NameConverterInterface $nameConverter = null,
  49. bool $useValidationGroups = false,
  50. ClassMetadataFactoryInterface $classMetadataFactory = null
  51. ) {
  52. $this->propertyInfo = $propertyInfo;
  53. $this->doctrineReader = $reader;
  54. $this->propertyDescribers = $propertyDescribers;
  55. $this->mediaTypes = $mediaTypes;
  56. $this->nameConverter = $nameConverter;
  57. $this->useValidationGroups = $useValidationGroups;
  58. $this->classMetadataFactory = $classMetadataFactory;
  59. }
  60. public function describe(Model $model, OA\Schema $schema)
  61. {
  62. $class = $model->getType()->getClassName();
  63. $schema->_context->class = $class;
  64. $context = ['serializer_groups' => null];
  65. if (null !== $model->getGroups()) {
  66. $context['serializer_groups'] = array_filter($model->getGroups(), 'is_string');
  67. }
  68. $reflClass = new \ReflectionClass($class);
  69. $annotationsReader = new AnnotationsReader(
  70. $this->doctrineReader,
  71. $this->modelRegistry,
  72. $this->mediaTypes,
  73. $this->useValidationGroups
  74. );
  75. $classResult = $annotationsReader->updateDefinition($reflClass, $schema);
  76. if (!$classResult->shouldDescribeModelProperties()) {
  77. return;
  78. }
  79. $schema->type = 'object';
  80. $mapping = false;
  81. if (null !== $this->classMetadataFactory) {
  82. $mapping = $this->classMetadataFactory
  83. ->getMetadataFor($class)
  84. ->getClassDiscriminatorMapping();
  85. }
  86. if ($mapping && Generator::UNDEFINED === $schema->discriminator) {
  87. $this->applyOpenApiDiscriminator(
  88. $model,
  89. $schema,
  90. $this->modelRegistry,
  91. $mapping->getTypeProperty(),
  92. $mapping->getTypesMapping()
  93. );
  94. }
  95. $propertyInfoProperties = $this->propertyInfo->getProperties($class, $context);
  96. if (null === $propertyInfoProperties) {
  97. return;
  98. }
  99. // Fix for https://github.com/nelmio/NelmioApiDocBundle/issues/1756
  100. // The SerializerExtractor does expose private/protected properties for some reason, so we eliminate them here
  101. $propertyInfoProperties = array_intersect($propertyInfoProperties, $this->propertyInfo->getProperties($class, []) ?? []);
  102. foreach ($propertyInfoProperties as $propertyName) {
  103. $serializedName = null !== $this->nameConverter ? $this->nameConverter->normalize($propertyName, $class, null, null !== $model->getGroups() ? ['groups' => $model->getGroups()] : []) : $propertyName;
  104. $reflections = $this->getReflections($reflClass, $propertyName);
  105. // Check if a custom name is set
  106. foreach ($reflections as $reflection) {
  107. $serializedName = $annotationsReader->getPropertyName($reflection, $serializedName);
  108. }
  109. $property = Util::getProperty($schema, $serializedName);
  110. // Interpret additional options
  111. $groups = $model->getGroups();
  112. if (isset($groups[$propertyName]) && is_array($groups[$propertyName])) {
  113. $groups = $model->getGroups()[$propertyName];
  114. }
  115. foreach ($reflections as $reflection) {
  116. $annotationsReader->updateProperty($reflection, $property, $groups);
  117. }
  118. // If type manually defined
  119. if (Generator::UNDEFINED !== $property->type || Generator::UNDEFINED !== $property->ref) {
  120. continue;
  121. }
  122. $types = $this->propertyInfo->getTypes($class, $propertyName);
  123. if (null === $types || 0 === count($types)) {
  124. 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));
  125. }
  126. $this->describeProperty($types, $model, $property, $propertyName);
  127. }
  128. }
  129. /**
  130. * @return \ReflectionProperty[]|\ReflectionMethod[]
  131. */
  132. private function getReflections(\ReflectionClass $reflClass, string $propertyName): array
  133. {
  134. $reflections = [];
  135. if ($reflClass->hasProperty($propertyName)) {
  136. $reflections[] = $reflClass->getProperty($propertyName);
  137. }
  138. $camelProp = $this->camelize($propertyName);
  139. foreach (['', 'get', 'is', 'has', 'can', 'add', 'remove', 'set'] as $prefix) {
  140. if ($reflClass->hasMethod($prefix.$camelProp)) {
  141. $reflections[] = $reflClass->getMethod($prefix.$camelProp);
  142. }
  143. }
  144. return $reflections;
  145. }
  146. /**
  147. * Camelizes a given string.
  148. */
  149. private function camelize(string $string): string
  150. {
  151. return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
  152. }
  153. /**
  154. * @param Type[] $types
  155. */
  156. private function describeProperty(array $types, Model $model, OA\Schema $property, string $propertyName)
  157. {
  158. foreach ($this->propertyDescribers as $propertyDescriber) {
  159. if ($propertyDescriber instanceof ModelRegistryAwareInterface) {
  160. $propertyDescriber->setModelRegistry($this->modelRegistry);
  161. }
  162. if ($propertyDescriber->supports($types)) {
  163. try {
  164. $propertyDescriber->describe($types, $property, $model->getGroups());
  165. } catch (UndocumentedArrayItemsException $e) {
  166. if (null !== $e->getClass()) {
  167. throw $e; // This exception is already complete
  168. }
  169. throw new UndocumentedArrayItemsException($model->getType()->getClassName(), sprintf('%s%s', $propertyName, $e->getPath()));
  170. }
  171. return;
  172. }
  173. }
  174. throw new \Exception(sprintf('Type "%s" is not supported in %s::$%s. You may use the `@OA\Property(type="")` annotation to specify it manually.', $types[0]->getBuiltinType(), $model->getType()->getClassName(), $propertyName));
  175. }
  176. public function supports(Model $model): bool
  177. {
  178. return Type::BUILTIN_TYPE_OBJECT === $model->getType()->getBuiltinType()
  179. && (class_exists($model->getType()->getClassName()) || interface_exists($model->getType()->getClassName()));
  180. }
  181. }