JsonSerializableNormalizer.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Serializer\Normalizer;
  11. use Symfony\Component\Serializer\Exception\InvalidArgumentException;
  12. use Symfony\Component\Serializer\Exception\LogicException;
  13. /**
  14. * A normalizer that uses an objects own JsonSerializable implementation.
  15. *
  16. * @author Fred Cox <mcfedr@gmail.com>
  17. */
  18. class JsonSerializableNormalizer extends AbstractNormalizer
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function normalize($object, string $format = null, array $context = [])
  24. {
  25. if ($this->isCircularReference($object, $context)) {
  26. return $this->handleCircularReference($object);
  27. }
  28. if (!$object instanceof \JsonSerializable) {
  29. throw new InvalidArgumentException(sprintf('The object must implement "%s".', \JsonSerializable::class));
  30. }
  31. if (!$this->serializer instanceof NormalizerInterface) {
  32. throw new LogicException('Cannot normalize object because injected serializer is not a normalizer.');
  33. }
  34. return $this->serializer->normalize($object->jsonSerialize(), $format, $context);
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function supportsNormalization($data, string $format = null)
  40. {
  41. return $data instanceof \JsonSerializable;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function supportsDenormalization($data, string $type, string $format = null)
  47. {
  48. return false;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function denormalize($data, string $type, string $format = null, array $context = [])
  54. {
  55. throw new LogicException(sprintf('Cannot denormalize with "%s".', \JsonSerializable::class));
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function hasCacheableSupportsMethod(): bool
  61. {
  62. return __CLASS__ === static::class;
  63. }
  64. }