<?php

declare(strict_types=1);

namespace Itdatex\EInvoiceCore\Vendor\JMS\Serializer\Construction;

use Itdatex\EInvoiceCore\Vendor\Doctrine\Instantiator\Instantiator;
use Itdatex\EInvoiceCore\Vendor\JMS\Serializer\DeserializationContext;
use Itdatex\EInvoiceCore\Vendor\JMS\Serializer\Metadata\ClassMetadata;
use Itdatex\EInvoiceCore\Vendor\JMS\Serializer\Visitor\DeserializationVisitorInterface;

final class UnserializeObjectConstructor implements ObjectConstructorInterface
{
    /** @var Instantiator */
    private $instantiator;

    /**
     * {@inheritdoc}
     */
    public function construct(DeserializationVisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context): ?object
    {
        return $this->getInstantiator()->instantiate($metadata->name);
    }

    private function getInstantiator(): Instantiator
    {
        if (null === $this->instantiator) {
            $this->instantiator = new Instantiator();
        }

        return $this->instantiator;
    }
}
