|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Sylius package. |
| 5 | + * |
| 6 | + * (c) Sylius Sp. z o.o. |
| 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 Sylius\ImportExport\Denormalizer; |
| 15 | + |
| 16 | +use Doctrine\ORM\EntityManagerInterface; |
| 17 | +use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; |
| 18 | +use Webmozart\Assert\Assert; |
| 19 | + |
| 20 | +final readonly class DefaultResourceDenormalizer implements ResourceDenormalizerInterface |
| 21 | +{ |
| 22 | + public function __construct( |
| 23 | + private DenormalizerInterface $denormalizer, |
| 24 | + private RelationResolverInterface $relationResolver, |
| 25 | + private EntityManagerInterface $entityManager, |
| 26 | + ) { |
| 27 | + } |
| 28 | + |
| 29 | + public function denormalize(array $data, string $resourceClass): object |
| 30 | + { |
| 31 | + $metadata = $this->entityManager->getClassMetadata($resourceClass); |
| 32 | + $processedData = []; |
| 33 | + |
| 34 | + foreach ($data as $field => $value) { |
| 35 | + if (null === $value || '' === $value) { |
| 36 | + continue; |
| 37 | + } |
| 38 | + |
| 39 | + if ($metadata->hasAssociation($field)) { |
| 40 | + $associationMapping = $metadata->getAssociationMapping($field); |
| 41 | + $targetEntity = $associationMapping['targetEntity']; |
| 42 | + Assert::string($targetEntity); |
| 43 | + |
| 44 | + if ($metadata->isCollectionValuedAssociation($field)) { |
| 45 | + if (is_array($value) && !empty($value)) { |
| 46 | + $processedData[$field] = $this->relationResolver->resolveCollection($targetEntity, $value); |
| 47 | + } else { |
| 48 | + $processedData[$field] = []; |
| 49 | + } |
| 50 | + } else { |
| 51 | + if (is_array($value) && !empty($value)) { |
| 52 | + $processedData[$field] = $this->relationResolver->resolveEntity($targetEntity, $value); |
| 53 | + } |
| 54 | + } |
| 55 | + } elseif (is_array($value)) { |
| 56 | + $processedData[$field] = $this->processNestedArray($value); |
| 57 | + } else { |
| 58 | + $processedData[$field] = $value; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + $result = $this->denormalizer->denormalize($processedData, $resourceClass); |
| 63 | + Assert::object($result); |
| 64 | + |
| 65 | + return $result; |
| 66 | + } |
| 67 | + |
| 68 | + private function processNestedArray(array $data): array |
| 69 | + { |
| 70 | + return $data; |
| 71 | + } |
| 72 | + |
| 73 | + public function supports(string $resourceClass): bool |
| 74 | + { |
| 75 | + return true; |
| 76 | + } |
| 77 | +} |
0 commit comments