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

use Chill\DocStoreBundle\Entity\StoredObject;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception;
use Symfony\Component\Form\FormInterface;

class StoredObjectDataMapper implements DataMapperInterface
{
    public function __construct() {}

    /**
     * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances
     */
    public function mapDataToForms($viewData, \Traversable $forms)
    {
        if (null === $viewData) {
            return;
        }

        if (!$viewData instanceof StoredObject) {
            throw new Exception\UnexpectedTypeException($viewData, StoredObject::class);
        }

        $forms = iterator_to_array($forms);
        if (array_key_exists('title', $forms)) {
            $forms['title']->setData($viewData->getTitle());
        }
        $forms['stored_object']->setData($viewData);
    }

    /**
     * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances
     */
    public function mapFormsToData(\Traversable $forms, &$viewData)
    {
        $forms = iterator_to_array($forms);

        if (!(null === $viewData || $viewData instanceof StoredObject)) {
            throw new Exception\UnexpectedTypeException($viewData, StoredObject::class);
        }

        if (null === $forms['stored_object']->getData()) {
            return;
        }

        /* @var StoredObject $viewData */
        $viewData = $forms['stored_object']->getData();

        if (array_key_exists('title', $forms)) {
            $viewData->setTitle($forms['title']->getData());
        }
    }
}
