Test Setup Failed
Branch master (6c0567)
by Dawid
01:41
created

LazyServiceFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Spiechu\LazyPimple\Factory;
4
5
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
6
use ProxyManager\Proxy\VirtualProxyInterface;
7
8
class LazyServiceFactory
9
{
10
    /**
11
     * @var LazyLoadingValueHolderFactory
12
     */
13
    protected $lazyLoadingFactory;
14
15
    /**
16
     * @param LazyLoadingValueHolderFactory $lazyLoadingFactory
17
     */
18 3
    public function __construct(LazyLoadingValueHolderFactory $lazyLoadingFactory)
19
    {
20 3
        $this->lazyLoadingFactory = $lazyLoadingFactory;
21 3
    }
22
23
    /**
24
     * @param string   $className
25
     * @param callable $definition
26
     *
27
     * @throws \InvalidArgumentException When $definition callable doesn't return $className instance
28
     *
29
     * @return VirtualProxyInterface
30
     */
31 3
    public function getLazyServiceDefinition(string $className, callable $definition): VirtualProxyInterface
32
    {
33 3
        return $this->lazyLoadingFactory->createProxy(
34 3
            $className,
35
            // this fancy method signature is required by lazy loading factory
36
            function (&$wrappedObject, $proxy, $method, $parameters, &$initializer) use ($className, $definition) {
37 1
                $wrappedObject = $definition();
38 1
                $initializer = null;
39
40
                // extra defensive programming in action
41 1
                if (!$wrappedObject instanceof $className) {
42
                    throw new \InvalidArgumentException(sprintf(
43
                        'Object "%s" is not instance of "%s"',
44
                        \is_object($wrappedObject) ? \get_class($wrappedObject) : \gettype($wrappedObject),
45
                        $className
46
                    ));
47
                }
48
49 1
                return true;
50 3
            }
51
        );
52
    }
53
}
54