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

use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ReadableCollection;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;

/**
 * Normalize a collection for docgen format.
 */
class CollectionDocGenNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
    use NormalizerAwareTrait;

    /**
     * @param Collection  $object
     * @param string|null $format
     *
     * @return array|\ArrayObject|bool|float|int|string|void|null
     */
    public function normalize($object, $format = null, array $context = [])
    {
        $data = [];

        if (null === $object || 0 === $object->count()) {
            return $data;
        }

        foreach ($object->getIterator() as $item) {
            $data[] = $this->normalizer->normalize($item, $format, $context);
        }

        return $data;
    }

    public function supportsNormalization($data, $format = null, array $context = [])
    {
        if ('docgen' !== $format) {
            return false;
        }

        return $data instanceof ReadableCollection
            || (null === $data && Collection::class === ($context['docgen:expects'] ?? null))
            || (null === $data && ReadableCollection::class === ($context['docgen:expects'] ?? null))
        ;
    }
}
