<?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\PersonBundle\Form\DataMapper;

use Chill\PersonBundle\Entity\PersonAltName;
use Symfony\Component\Form\DataMapperInterface;

class PersonAltNameDataMapper implements DataMapperInterface
{
    public function mapDataToForms($viewData, \Traversable $forms): void
    {
        if (null === $viewData) {
            return;
        }

        if (!is_array($viewData)) {
            throw new \InvalidArgumentException('View data must be an array');
        }

        foreach ($forms as $key => $form) {
            $personAltName = $viewData[$key];
            if (!$personAltName instanceof PersonAltName) {
                throw new \InvalidArgumentException('PersonAltName must be an instance of PersonAltName');
            }
            $form->setData($personAltName->getLabel());
        }
    }

    public function mapFormsToData(\Traversable $forms, &$viewData): void
    {
        foreach ($forms as $key => $form) {
            $personAltName = array_find($viewData, fn (PersonAltName $altName) => $altName->getKey() === $key);
            $personAltName->setLabel($form->getData());
        }
    }
}
