CustomNormalizer.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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\SerializerAwareInterface;
  12. use Symfony\Component\Serializer\SerializerAwareTrait;
  13. /**
  14. * @author Jordi Boggiano <j.boggiano@seld.be>
  15. */
  16. class CustomNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface, CacheableSupportsMethodInterface
  17. {
  18. use ObjectToPopulateTrait;
  19. use SerializerAwareTrait;
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function normalize($object, string $format = null, array $context = [])
  24. {
  25. return $object->normalize($this->serializer, $format, $context);
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function denormalize($data, string $type, string $format = null, array $context = [])
  31. {
  32. $object = $this->extractObjectToPopulate($type, $context) ?: new $type();
  33. $object->denormalize($this->serializer, $data, $format, $context);
  34. return $object;
  35. }
  36. /**
  37. * Checks if the given class implements the NormalizableInterface.
  38. *
  39. * @param mixed $data Data to normalize
  40. * @param string $format The format being (de-)serialized from or into
  41. *
  42. * @return bool
  43. */
  44. public function supportsNormalization($data, string $format = null)
  45. {
  46. return $data instanceof NormalizableInterface;
  47. }
  48. /**
  49. * Checks if the given class implements the DenormalizableInterface.
  50. *
  51. * @param mixed $data Data to denormalize from
  52. * @param string $type The class to which the data should be denormalized
  53. * @param string $format The format being deserialized from
  54. *
  55. * @return bool
  56. */
  57. public function supportsDenormalization($data, string $type, string $format = null)
  58. {
  59. return is_subclass_of($type, DenormalizableInterface::class);
  60. }
  61. /**
  62. * {@inheritdoc}
  63. */
  64. public function hasCacheableSupportsMethod(): bool
  65. {
  66. return __CLASS__ === static::class;
  67. }
  68. }