InitializedObjectConstructor.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. namespace JMS\Serializer\Tests\Fixtures;
  3. use JMS\Serializer\Construction\ObjectConstructorInterface;
  4. use JMS\Serializer\DeserializationContext;
  5. use JMS\Serializer\Metadata\ClassMetadata;
  6. use JMS\Serializer\VisitorInterface;
  7. /**
  8. * Object constructor that allows deserialization into already constructed
  9. * objects passed through the deserialization context
  10. */
  11. class InitializedObjectConstructor implements ObjectConstructorInterface
  12. {
  13. private $fallbackConstructor;
  14. /**
  15. * Constructor.
  16. *
  17. * @param ObjectConstructorInterface $fallbackConstructor Fallback object constructor
  18. */
  19. public function __construct(ObjectConstructorInterface $fallbackConstructor)
  20. {
  21. $this->fallbackConstructor = $fallbackConstructor;
  22. }
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function construct(VisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context)
  27. {
  28. if ($context->attributes->containsKey('target') && $context->getDepth() === 1) {
  29. return $context->attributes->get('target')->get();
  30. }
  31. return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
  32. }
  33. }