InjectLazy::getFactory()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
namespace mxdiModule\Annotation;
3
4
use mxdiModule\Exception\CannotGetValue;
5
use mxdiModule\Factory\ProxyFactory;
6
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
7
use ProxyManager\Proxy\LazyLoadingInterface;
8
use Zend\ServiceManager\ServiceLocatorInterface;
9
10
/**
11
 * @Annotation
12
 * @Target({"PROPERTY", "ANNOTATION", "METHOD"})
13
 */
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)
71
    {
72 5
        $this->factory = $factory;
73 5
    }
74
}
75