| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\Serializer\Normalizer; |
| 13 |
|
| 14 |
use BcMath\Number; |
| 15 |
use Symfony\Component\Serializer\Exception\InvalidArgumentException; |
| 16 |
use Symfony\Component\Serializer\Exception\NotNormalizableValueException; |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
final class NumberNormalizer implements NormalizerInterface, DenormalizerInterface |
| 22 |
{ |
| 23 |
public function getSupportedTypes(?string $format): array |
| 24 |
{ |
| 25 |
return [ |
| 26 |
Number::class => true, |
| 27 |
\GMP::class => true, |
| 28 |
]; |
| 29 |
} |
| 30 |
|
| 31 |
public function normalize(mixed $data, ?string $format = null, array $context = []): string |
| 32 |
{ |
| 33 |
if (!$data instanceof Number && !$data instanceof \GMP) { |
| 34 |
throw new InvalidArgumentException(\sprintf('The data must be an instance of "%s" or "%s".', Number::class, \GMP::class)); |
| 35 |
} |
| 36 |
|
| 37 |
return (string) $data; |
| 38 |
} |
| 39 |
|
| 40 |
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool |
| 41 |
{ |
| 42 |
return $data instanceof Number || $data instanceof \GMP; |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): Number|\GMP |
| 49 |
{ |
| 50 |
if (!\is_string($data) && !\is_int($data)) { |
| 51 |
throw $this->createNotNormalizableValueException($type, $data, $context); |
| 52 |
} |
| 53 |
|
| 54 |
try { |
| 55 |
return match ($type) { |
| 56 |
Number::class => new Number($data), |
| 57 |
\GMP::class => new \GMP($data), |
| 58 |
default => throw new InvalidArgumentException(\sprintf('Only "%s" and "%s" types are supported.', Number::class, \GMP::class)), |
| 59 |
}; |
| 60 |
} catch (\ValueError $e) { |
| 61 |
throw $this->createNotNormalizableValueException($type, $data, $context, $e); |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool |
| 66 |
{ |
| 67 |
return \in_array($type, [Number::class, \GMP::class], true) && null !== $data; |
| 68 |
} |
| 69 |
|
| 70 |
private function createNotNormalizableValueException(string $type, mixed $data, array $context, ?\Throwable $previous = null): NotNormalizableValueException |
| 71 |
{ |
| 72 |
$message = match ($type) { |
| 73 |
Number::class => 'The data must be a "string" representing a decimal number, or an "int".', |
| 74 |
\GMP::class => 'The data must be a "string" representing an integer, or an "int".', |
| 75 |
}; |
| 76 |
|
| 77 |
return NotNormalizableValueException::createForUnexpectedDataType($message, $data, ['string', 'int'], $context['deserialization_path'] ?? null, true, 0, $previous); |
| 78 |
} |
| 79 |
} |