<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Form\Type\DataTransformer;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class ObjectToIdTransformer implements DataTransformerInterface
{
    public function __construct(private readonly EntityManagerInterface $em, private readonly ?string $class = null) {}

    /**
     * Transforms a string (id) to an object.
     *
     * @param string $id
     *
     * @throws TransformationFailedException if object is not found
     */
    public function reverseTransform($id): ?object
    {
        if (null === $id) {
            return null;
        }

        $object = $this->em
            ->getRepository($this->class)
            ->find($id);

        if (null === $object) {
            throw new TransformationFailedException();
        }

        return $object;
    }

    /**
     * Transforms an object to a string (id).
     *
     * @return string
     */
    public function transform($object)
    {
        if (null === $object) {
            return '';
        }

        return $object->getId();
    }
}
