JsonDeNormalizer.php 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 Hyperf\Contract\NormalizerInterface;
  13. class JsonDeNormalizer implements NormalizerInterface
  14. {
  15. public function normalize($object)
  16. {
  17. return $object;
  18. }
  19. public function denormalize($data, string $class)
  20. {
  21. return match ($class) {
  22. 'int' => (int) $data,
  23. 'string' => (string) $data,
  24. 'float' => (float) $data,
  25. 'array' => (array) $data,
  26. 'bool' => (bool) $data,
  27. 'mixed' => $data,
  28. default => $this->from($data, $class),
  29. };
  30. }
  31. private function from(mixed $data, string $class): mixed
  32. {
  33. if (method_exists($class, 'jsonDeSerialize')) {
  34. return $class::jsonDeSerialize($data);
  35. }
  36. return $data;
  37. }
  38. }