|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace ApiPlatform\State\Provider; |
| 15 | + |
| 16 | +use ApiPlatform\Doctrine\Odm\State\Options as OdmOptions; |
| 17 | +use ApiPlatform\Doctrine\Orm\State\Options; |
| 18 | +use ApiPlatform\Metadata\Operation; |
| 19 | +use ApiPlatform\State\Pagination\ArrayPaginator; |
| 20 | +use ApiPlatform\State\Pagination\PaginatorInterface; |
| 21 | +use ApiPlatform\State\ProviderInterface; |
| 22 | +use Symfony\Component\ObjectMapper\Attribute\Map; |
| 23 | +use Symfony\Component\ObjectMapper\ObjectMapperInterface; |
| 24 | + |
| 25 | +final class ObjectMapperProvider implements ProviderInterface |
| 26 | +{ |
| 27 | + public function __construct( |
| 28 | + private readonly ObjectMapperInterface $objectMapper, |
| 29 | + private readonly ProviderInterface $decorated, |
| 30 | + ) { |
| 31 | + } |
| 32 | + |
| 33 | + public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null |
| 34 | + { |
| 35 | + $data = $this->decorated->provide($operation, $uriVariables, $context); |
| 36 | + |
| 37 | + if(!is_object($data)) { |
| 38 | + return $data; |
| 39 | + } |
| 40 | + |
| 41 | + $entityClass = $operation->getClass(); |
| 42 | + if (($options = $operation->getStateOptions()) && $options instanceof Options && $options->getEntityClass()) { |
| 43 | + $entityClass = $options->getEntityClass(); |
| 44 | + } |
| 45 | + |
| 46 | + if (($options = $operation->getStateOptions()) && $options instanceof OdmOptions && $options->getDocumentClass()) { |
| 47 | + $entityClass = $options->getDocumentClass(); |
| 48 | + } |
| 49 | + |
| 50 | + if (!(new \ReflectionClass($entityClass))->getAttributes(Map::class)) { |
| 51 | + return $data; |
| 52 | + } |
| 53 | + |
| 54 | + if ($data instanceof PaginatorInterface) { |
| 55 | + return new ArrayPaginator(array_map(fn($v) => $this->objectMapper->map($v), iterator_to_array($data)), 0, \count($data)); |
| 56 | + } |
| 57 | + |
| 58 | + return $this->objectMapper->map($data); |
| 59 | + } |
| 60 | +} |
| 61 | + |
0 commit comments