Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
13.33% |
2 / 15 |
|
50.00% |
2 / 4 |
CRAP | |
0.00% |
0 / 1 |
| DurationNormalizer | |
13.33% |
2 / 15 |
|
50.00% |
2 / 4 |
38.90 | |
0.00% |
0 / 1 |
| supportsNormalization | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| supportsDenormalization | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| normalize | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| denormalize | |
0.00% |
0 / 12 |
|
0.00% |
0 / 1 |
20 | |||
| 1 | <?php |
| 2 | namespace Apie\Serializer\Normalizers; |
| 3 | |
| 4 | use Apie\Core\Lists\ItemHashmap; |
| 5 | use Apie\Core\Lists\ItemList; |
| 6 | use Apie\Core\ValueObjects\Utils; |
| 7 | use Apie\Serializer\Context\ApieSerializerContext; |
| 8 | use Apie\Serializer\Dto\DurationDto; |
| 9 | use Apie\Serializer\Interfaces\DenormalizerInterface; |
| 10 | use Apie\Serializer\Interfaces\NormalizerInterface; |
| 11 | use Apie\TypeConverter\ReflectionTypeFactory; |
| 12 | use Psr\Http\Message\UploadedFileInterface; |
| 13 | use Time\Duration; |
| 14 | |
| 15 | class DurationNormalizer implements NormalizerInterface, DenormalizerInterface |
| 16 | { |
| 17 | public function supportsNormalization(mixed $object, ApieSerializerContext $apieSerializerContext): bool |
| 18 | { |
| 19 | return $object instanceof Duration; |
| 20 | } |
| 21 | |
| 22 | public function supportsDenormalization(string|int|float|bool|null|ItemList|ItemHashmap|UploadedFileInterface $object, string $desiredType, ApieSerializerContext $apieSerializerContext): bool |
| 23 | { |
| 24 | return $desiredType === Duration::class; |
| 25 | } |
| 26 | |
| 27 | public function normalize(mixed $object, ApieSerializerContext $apieSerializerContext): ItemHashmap |
| 28 | { |
| 29 | return $apieSerializerContext->normalizeAgain(json_decode(json_encode($object), true)); |
| 30 | } |
| 31 | |
| 32 | public function denormalize(string|int|float|bool|null|ItemList|ItemHashmap|UploadedFileInterface $object, string $desiredType, ApieSerializerContext $apieSerializerContext): mixed |
| 33 | { |
| 34 | if (is_numeric($object)) { |
| 35 | $object = (float) $object; |
| 36 | $result = Duration::fromNanoseconds((int) abs(1000 * $object)); |
| 37 | if ($object < 0) { |
| 38 | $result = $result->negate(); |
| 39 | } |
| 40 | return $result; |
| 41 | } |
| 42 | $array = Utils::toArray($object); |
| 43 | $dto = $apieSerializerContext->denormalizeFromTypehint($array, ReflectionTypeFactory::createReflectionType(DurationDto::class)); |
| 44 | |
| 45 | $result = Duration::fromSeconds($dto->seconds, $dto->nanoseconds); |
| 46 | if ($dto->negative) { |
| 47 | $result = $result->negate(); |
| 48 | } |
| 49 | return $result; |
| 50 | } |
| 51 | } |