Completed
Push — master ( b8df74...d61374 )
by Dawid
01:47
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 4
    public function __construct(LazyLoadingValueHolderFactory $lazyLoadingFactory)
19
    {
20 4
        $this->lazyLoadingFactory = $lazyLoadingFactory;
21 4
    }
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 4
    public function getLazyServiceDefinition(string $className, callable $definition): VirtualProxyInterface
32
    {
33 4
        return $this->lazyLoadingFactory->createProxy(
34 4
            $className,
35
            // this fancy method signature is required by lazy loading factory
36
            static 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 View Code Duplication
                if (!$wrappedObject instanceof $className) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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 4
            }
51
        );
52
    }
53
}
54