NelmioApiDocBundle/PropertyDescriber/ArrayPropertyDescriber.php

72 lines
2.3 KiB
PHP
Raw Normal View History

2019-12-13 22:45:32 +01:00
<?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\PropertyDescriber;
2020-02-18 21:08:48 +01:00
use Nelmio\ApiDocBundle\Describer\ModelRegistryAwareInterface;
use Nelmio\ApiDocBundle\Describer\ModelRegistryAwareTrait;
use Nelmio\ApiDocBundle\Exception\UndocumentedArrayItemsException;
use Nelmio\ApiDocBundle\OpenApiPhp\Util;
use OpenApi\Annotations as OA;
2019-12-13 22:45:32 +01:00
2020-02-18 21:08:48 +01:00
class ArrayPropertyDescriber implements PropertyDescriberInterface, ModelRegistryAwareInterface
2019-12-13 22:45:32 +01:00
{
2020-02-18 21:08:48 +01:00
use ModelRegistryAwareTrait;
use NullablePropertyTrait;
2020-02-18 21:08:48 +01:00
2019-12-13 22:45:32 +01:00
/** @var PropertyDescriberInterface[] */
private $propertyDescribers;
2020-02-18 20:45:58 +01:00
public function __construct(iterable $propertyDescribers = [])
2019-12-13 22:45:32 +01:00
{
$this->propertyDescribers = $propertyDescribers;
}
public function describe(array $types, OA\Schema $property, array $groups = null)
2019-12-13 22:45:32 +01:00
{
// BC layer for symfony < 5.3
$type = method_exists($types[0], 'getCollectionValueTypes') ?
($types[0]->getCollectionValueTypes()[0] ?? null) :
$types[0]->getCollectionValueType();
2019-12-13 22:45:32 +01:00
if (null === $type) {
throw new UndocumentedArrayItemsException();
2019-12-13 22:45:32 +01:00
}
$property->type = 'array';
$this->setNullableProperty($types[0], $property);
$property = Util::getChild($property, OA\Items::class);
2019-12-13 22:45:32 +01:00
foreach ($this->propertyDescribers as $propertyDescriber) {
2020-02-18 21:08:48 +01:00
if ($propertyDescriber instanceof ModelRegistryAwareInterface) {
$propertyDescriber->setModelRegistry($this->modelRegistry);
}
if ($propertyDescriber->supports([$type])) {
try {
2020-12-10 22:28:55 +01:00
$propertyDescriber->describe([$type], $property, $groups);
} catch (UndocumentedArrayItemsException $e) {
if (null !== $e->getClass()) {
throw $e; // This exception is already complete
}
2020-11-20 17:10:21 +01:00
throw new UndocumentedArrayItemsException(null, sprintf('%s[]', $e->getPath()));
}
2019-12-13 22:45:32 +01:00
break;
}
}
}
public function supports(array $types): bool
2019-12-13 22:45:32 +01:00
{
return 1 === count($types) && $types[0]->isCollection();
2019-12-13 22:45:32 +01:00
}
2019-12-13 22:48:28 +01:00
}