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