<?php

declare(strict_types=1);

namespace KupShop\KupShopBundle\Util\Entity;

use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class EntityUtil
{
    /**
     * @template T
     *
     * @param class-string<T> $class
     *
     * @return T
     *
     * @throws ExceptionInterface
     */
    public function createEntity(array $data, string $class, ?NameConverterInterface $nameConverter = null)
    {
        static $serializer = [];

        $key = $nameConverter ? $nameConverter::class : null;

        if (!($serializer[$key] ?? false)) {
            $normalizers = [new ObjectNormalizer(nameConverter: $nameConverter)];
            $serializer[$key] = new Serializer($normalizers);
        }

        return $serializer[$key]->denormalize($data, $class);
    }

    public function createArray(object $object)
    {
        static $serializer;

        if (!$serializer) {
            $normalizers = [new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter())];
            $serializer = new Serializer($normalizers);
        }

        return $serializer->normalize($object);
    }
}
