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

use Chill\MainBundle\Entity\Scope;
use Symfony\Component\Form\DataMapperInterface;

class ScopePickerDataMapper implements DataMapperInterface
{
    public function __construct(private readonly ?Scope $scope = null) {}

    public function mapDataToForms($data, \Traversable $forms)
    {
        $forms = iterator_to_array($forms);

        if ($this->scope instanceof Scope) {
            $forms['scope']->setData($this->scope);

            return;
        }

        if (null === $data) {
            return;
        }

        if ($data instanceof Scope) {
            $forms['scope']->setData($data);
        }
    }

    public function mapFormsToData(\Traversable $forms, &$data)
    {
        $forms = iterator_to_array($forms);

        if (isset($forms['scope'])) {
            if ($this->scope instanceof Scope) {
                $data = $this->scope;
            } else {
                $data = $forms['scope']->getData();
            }
        }
    }
}
