<?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\TicketBundle\Serializer\Normalizer;

use Chill\PersonBundle\Entity\Person;
use Chill\TicketBundle\Action\Ticket\SetPersonsCommand;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class SetPersonsCommandDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
    use DenormalizerAwareTrait;

    public function denormalize($data, string $type, ?string $format = null, array $context = [])
    {
        if (null === $data) {
            return null;
        }

        if (!array_key_exists('persons', $data)) {
            throw new UnexpectedValueException("key 'persons' does exists");
        }

        if (!is_array($data['persons'])) {
            throw new UnexpectedValueException("key 'persons' must be an array");
        }

        $persons = [];
        foreach ($data['persons'] as $person) {
            $persons[] = $this->denormalizer->denormalize($person, Person::class, $format, $context);
        }

        return new SetPersonsCommand($persons);
    }

    public function supportsDenormalization($data, string $type, ?string $format = null)
    {
        return SetPersonsCommand::class === $type;
    }
}
