UnwrappingDenormalizer.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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\PropertyAccess\PropertyAccess;
  12. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  13. use Symfony\Component\Serializer\SerializerAwareInterface;
  14. use Symfony\Component\Serializer\SerializerAwareTrait;
  15. /**
  16. * @author Eduard Bulava <bulavaeduard@gmail.com>
  17. */
  18. final class UnwrappingDenormalizer implements DenormalizerInterface, SerializerAwareInterface, CacheableSupportsMethodInterface
  19. {
  20. use SerializerAwareTrait;
  21. public const UNWRAP_PATH = 'unwrap_path';
  22. private $propertyAccessor;
  23. public function __construct(PropertyAccessorInterface $propertyAccessor = null)
  24. {
  25. $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function denormalize($data, $class, string $format = null, array $context = [])
  31. {
  32. $propertyPath = $context[self::UNWRAP_PATH];
  33. $context['unwrapped'] = true;
  34. if ($propertyPath) {
  35. if (!$this->propertyAccessor->isReadable($data, $propertyPath)) {
  36. return null;
  37. }
  38. $data = $this->propertyAccessor->getValue($data, $propertyPath);
  39. }
  40. return $this->serializer->denormalize($data, $class, $format, $context);
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function supportsDenormalization($data, $type, string $format = null, array $context = [])
  46. {
  47. return \array_key_exists(self::UNWRAP_PATH, $context) && !isset($context['unwrapped']);
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function hasCacheableSupportsMethod(): bool
  53. {
  54. return $this->serializer instanceof CacheableSupportsMethodInterface && $this->serializer->hasCacheableSupportsMethod();
  55. }
  56. }