ScalarNormalizer.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Serializer;
  12. use ArrayObject;
  13. use Hyperf\Serializer\Contract\CacheableSupportsMethodInterface;
  14. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  15. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  16. use function get_class;
  17. use function is_scalar;
  18. class ScalarNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
  19. {
  20. public function hasCacheableSupportsMethod(): bool
  21. {
  22. return get_class($this) === __CLASS__;
  23. }
  24. public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
  25. {
  26. return match ($type) {
  27. 'int' => (int) $data,
  28. 'string' => (string) $data,
  29. 'float' => (float) $data,
  30. 'bool' => (bool) $data,
  31. default => $data,
  32. };
  33. }
  34. public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
  35. {
  36. return in_array($type, [
  37. 'int',
  38. 'string',
  39. 'float',
  40. 'bool',
  41. 'mixed',
  42. 'array', // TODO: Symfony\Component\Serializer\Normalizer\ArrayDenormalizer not support array, so it denormalized in ScalarNormalizer.
  43. ]);
  44. }
  45. public function normalize(mixed $object, ?string $format = null, array $context = []): null|array|ArrayObject|bool|float|int|string
  46. {
  47. return $object;
  48. }
  49. public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
  50. {
  51. return is_scalar($data);
  52. }
  53. public function getSupportedTypes(?string $format): array
  54. {
  55. return ['*' => static::class === __CLASS__];
  56. }
  57. }