1 | <?php |
||
14 | final class InjectLazy implements AnnotationInterface |
||
15 | { |
||
16 | /** @var string */ |
||
17 | public $value; |
||
18 | |||
19 | /** @var string */ |
||
20 | public $fqcn; |
||
21 | |||
22 | /** @var LazyLoadingValueHolderFactory */ |
||
23 | protected $factory; |
||
24 | |||
25 | /** |
||
26 | * Get the value. |
||
27 | * |
||
28 | * @param ServiceLocatorInterface|null $sm |
||
29 | * @return object |
||
30 | * |
||
31 | * @throws CannotGetValue |
||
32 | */ |
||
33 | 4 | public function getValue(ServiceLocatorInterface $sm) |
|
34 | { |
||
35 | 4 | $serviceName = $this->value; |
|
36 | 4 | $fqcn = $this->fqcn ?: $serviceName; |
|
37 | |||
38 | 4 | $initializer = function (& $object, LazyLoadingInterface $proxy) use ($sm, $serviceName) { |
|
39 | try { |
||
40 | 2 | $object = $sm->get($serviceName); |
|
41 | 2 | } catch (\Exception $e) { |
|
42 | 1 | return false; |
|
43 | } |
||
44 | |||
45 | 1 | $proxy->setProxyInitializer(null); |
|
46 | 1 | return true; |
|
47 | 4 | }; |
|
48 | |||
49 | 4 | return $this->getFactory($sm)->createProxy($fqcn, $initializer); |
|
50 | } |
||
51 | |||
52 | /** |
||
53 | * @param ServiceLocatorInterface $sm |
||
54 | * @return LazyLoadingValueHolderFactory |
||
55 | */ |
||
56 | 5 | public function getFactory(ServiceLocatorInterface $sm) |
|
57 | { |
||
58 | 5 | if (! $this->factory) { |
|
59 | /** @var LazyLoadingValueHolderFactory $factory */ |
||
60 | 3 | $factory = $sm->get(ProxyFactory::class); |
|
61 | 3 | $this->setFactory($factory); |
|
62 | 3 | } |
|
63 | |||
64 | 5 | return $this->factory; |
|
65 | } |
||
66 | |||
67 | /** |
||
68 | * @param LazyLoadingValueHolderFactory $factory |
||
69 | */ |
||
70 | 5 | public function setFactory(LazyLoadingValueHolderFactory $factory) |
|
74 | } |
||
75 |