<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\ObjectMapper;

use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;

final readonly class ObjectMapperProvider implements ObjectMapperInterface
{
    /**
     * @param iterable<StrategyObjectMapperInterface> $objectMappers
     */
    public function __construct(
        private ObjectMapperInterface $defaultMapper,
        #[AutowireIterator(tag: 'serenity.object_mapper')]
        private iterable $objectMappers,
    ) {
    }

    public function map(object $source, object|string|null $target = null): object
    {
        $targetClass = \is_object($target) ? $target::class : $target;

        foreach ($this->objectMappers as $objectMapper) {
            if (!$objectMapper instanceof StrategyObjectMapperInterface) {
                continue;
            }
            if ($objectMapper->supports($source::class, (string) $targetClass)) {
                return $objectMapper->map($source, $target);
            }
        }

        return $this->defaultMapper->map($source, $target);
    }
}
