Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.91% covered (success)
90.91%
10 / 11
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
PolymorphicObjectNormalizer
90.91% covered (success)
90.91%
10 / 11
50.00% covered (danger)
50.00%
1 / 2
5.02
0.00% covered (danger)
0.00%
0 / 1
 supportsDenormalization
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 denormalize
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
1<?php
2namespace Apie\Serializer\Normalizers;
3
4use Apie\Core\Exceptions\IndexNotFoundException;
5use Apie\Core\Lists\ItemHashmap;
6use Apie\Core\Lists\ItemList;
7use Apie\Core\Other\DiscriminatorMapping;
8use Apie\Core\Utils\EntityUtils;
9use Apie\Core\ValueObjects\Utils;
10use Apie\Serializer\Context\ApieSerializerContext;
11use Apie\Serializer\Exceptions\ValidationException;
12use Apie\Serializer\Interfaces\DenormalizerInterface;
13use Apie\TypeConverter\ReflectionTypeFactory;
14use Psr\Http\Message\UploadedFileInterface;
15use ReflectionClass;
16
17class PolymorphicObjectNormalizer implements DenormalizerInterface
18{
19    public function supportsDenormalization(string|int|float|bool|null|ItemList|ItemHashmap|UploadedFileInterface $object, string $desiredType, ApieSerializerContext $apieSerializerContext): bool
20    {
21        if ($object instanceof ItemHashmap && EntityUtils::isPolymorphicEntity($desiredType)) {
22            $refl = new ReflectionClass($desiredType);
23            return ($refl->getMethod('getDiscriminatorMapping')->getDeclaringClass()->name === $desiredType);
24        }
25
26        return false;
27    }
28
29    /**
30     * @param ItemHashMap $object
31     */
32    public function denormalize(string|int|float|bool|null|ItemList|ItemHashmap|UploadedFileInterface $object, string $desiredType, ApieSerializerContext $apieSerializerContext): mixed
33    {
34        $refl = new ReflectionClass($desiredType);
35        /** @var DiscriminatorMapping $mapping */
36        $mapping = $refl->getMethod('getDiscriminatorMapping')->invoke(null);
37        $propertyName = $mapping->getPropertyName();
38        if (!isset($object[$propertyName])) {
39            throw ValidationException::createFromArray(['id' => new IndexNotFoundException($propertyName)]);
40        }
41        $className = $mapping->getClassNameFromDiscriminator(Utils::toString($object[$propertyName]));
42        return $apieSerializerContext->denormalizeFromTypehint($object, ReflectionTypeFactory::createReflectionType($className));
43    }
44}