JsonSerializableNormalizer.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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, $format = null, array $context = array())
  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, $format = null)
  40. {
  41. return $data instanceof \JsonSerializable;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function supportsDenormalization($data, $type, $format = null)
  47. {
  48. return false;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function denormalize($data, $class, $format = null, array $context = array())
  54. {
  55. throw new LogicException(sprintf('Cannot denormalize with "%s".', \JsonSerializable::class));
  56. }
  57. }