1<?php
2
3declare(strict_types=1);
4
5namespace JMS\Serializer\EventDispatcher;
6
7use JMS\Serializer\Exception\InvalidArgumentException;
8use Psr\Container\ContainerInterface as PsrContainerInterface;
9use Symfony\Component\DependencyInjection\ContainerInterface;
10
11class LazyEventDispatcher extends EventDispatcher
12{
13    /**
14     * @var PsrContainerInterface|ContainerInterface
15     */
16    private $container;
17
18    /**
19     * @param PsrContainerInterface|ContainerInterface $container
20     */
21    public function __construct($container)
22    {
23        if (!$container instanceof PsrContainerInterface && !$container instanceof ContainerInterface) {
24            throw new InvalidArgumentException(sprintf('The container must be an instance of %s or %s (%s given).', PsrContainerInterface::class, ContainerInterface::class, \is_object($container) ? \get_class($container) : \gettype($container)));
25        }
26
27        $this->container = $container;
28    }
29
30    /**
31     * {@inheritdoc}
32     */
33    protected function initializeListeners(string $eventName, string $loweredClass, string $format): array
34    {
35        $listeners = parent::initializeListeners($eventName, $loweredClass, $format);
36
37        foreach ($listeners as &$listener) {
38            if (!\is_array($listener[0]) || !\is_string($listener[0][0])) {
39                continue;
40            }
41
42            if (!$this->container->has($listener[0][0])) {
43                continue;
44            }
45
46            $listener[0][0] = $this->container->get($listener[0][0]);
47        }
48
49        return $listeners;
50    }
51}
52