1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace JMS\Serializer\Handler; |
||
6 | |||
7 | use JMS\Serializer\Exception\InvalidArgumentException; |
||
8 | use Psr\Container\ContainerInterface as PsrContainerInterface; |
||
9 | use Symfony\Component\DependencyInjection\ContainerInterface; |
||
10 | |||
11 | final class LazyHandlerRegistry extends HandlerRegistry |
||
12 | { |
||
13 | /** |
||
14 | * @var PsrContainerInterface|ContainerInterface |
||
15 | */ |
||
16 | 4 | private $container; |
|
17 | |||
18 | 4 | /** |
|
19 | * @var array |
||
20 | */ |
||
21 | private $initializedHandlers = []; |
||
22 | 4 | ||
23 | 4 | /** |
|
24 | 4 | * @param PsrContainerInterface|ContainerInterface $container |
|
25 | * @param array $handlers |
||
26 | 4 | */ |
|
27 | public function __construct($container, array $handlers = []) |
||
28 | 4 | { |
|
29 | 4 | if (!$container instanceof PsrContainerInterface && !$container instanceof ContainerInterface) { |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
30 | 4 | 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))); |
|
31 | } |
||
32 | 4 | ||
33 | parent::__construct($handlers); |
||
34 | 4 | ||
35 | $this->container = $container; |
||
36 | } |
||
37 | |||
38 | 4 | /** |
|
39 | * {@inheritdoc} |
||
40 | */ |
||
41 | public function registerHandler(int $direction, string $typeName, string $format, $handler): void |
||
42 | 4 | { |
|
43 | 4 | parent::registerHandler($direction, $typeName, $format, $handler); |
|
44 | 2 | ||
45 | unset($this->initializedHandlers[$direction][$typeName][$format]); |
||
46 | } |
||
47 | 4 | ||
48 | /** |
||
49 | * {@inheritdoc} |
||
50 | */ |
||
51 | public function getHandler(int $direction, string $typeName, string $format) |
||
52 | { |
||
53 | if (isset($this->initializedHandlers[$direction][$typeName][$format])) { |
||
54 | return $this->initializedHandlers[$direction][$typeName][$format]; |
||
55 | } |
||
56 | |||
57 | if (!isset($this->handlers[$direction][$typeName][$format])) { |
||
58 | return null; |
||
59 | } |
||
60 | |||
61 | $handler = $this->handlers[$direction][$typeName][$format]; |
||
62 | if (\is_array($handler) && \is_string($handler[0]) && $this->container->has($handler[0])) { |
||
63 | $handler[0] = $this->container->get($handler[0]); |
||
64 | } |
||
65 | |||
66 | return $this->initializedHandlers[$direction][$typeName][$format] = $handler; |
||
67 | } |
||
68 | } |
||
69 |