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