<?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 Chill\MainBundle\Entity\Scope;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class ScopeTransformer implements DataTransformerInterface
{
    public function __construct(private readonly EntityManagerInterface $em) {}

    public function reverseTransform($id)
    {
        if (null === $id) {
            return null;
        }

        $scope = $this
            ->em
            ->getRepository(Scope::class)
            ->find($id);

        if (null === $scope) {
            throw new TransformationFailedException(sprintf('The scope with id '."'%d' were not found", $id));
        }

        return $scope;
    }

    public function transform($scope)
    {
        if (null === $scope) {
            return null;
        }

        return $scope->getId();
    }
}
