<?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\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\DataTransformerInterface;

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

    /**
     * Transforms a string (id) to an object (item).
     */
    public function reverseTransform($array)
    {
        $ret = new ArrayCollection();

        foreach ($array as $el) {
            $ret->add(
                $this->em
                    ->getRepository($this->class)
                    ->find($el)
            );
        }

        return $ret;
    }

    /**
     * Transforms an object (use) to a string (id).
     *
     * @param array $array
     */
    public function transform($array): array
    {
        $ret = [];

        foreach ($array as $el) {
            $ret[] = $el->getId();
        }

        return $ret;
    }
}
