Wrapper::__construct()   B
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
c 0
b 0
f 0
rs 8.8571
cc 5
eloc 9
nc 4
nop 2
1
<?php
2
3
namespace Isolate\LazyObjects;
4
5
use Isolate\LazyObjects\Exception\InvalidArgumentException;
6
use Isolate\LazyObjects\Proxy\Definition;
7
use Isolate\LazyObjects\Proxy\Factory;
8
use Isolate\LazyObjects\Exception\RuntimeException;
9
10
/**
11
 * @api
12
 */
13
class Wrapper
14
{
15
    /**
16
     * @var array|Definition[]
17
     */
18
    private $definitions;
19
20
    /**
21
     * @var Factory
22
     */
23
    private $factory;
24
25
    /**
26
     * @param Factory $factory
27
     * @param array $definitions
28
     * @throws InvalidArgumentException
29
     */
30
    public function __construct(Factory $factory, $definitions = [])
31
    {
32
        $this->definitions = [];
33
34
        if (!is_array($definitions) && !$definitions instanceof \Traversable) {
35
            throw new InvalidArgumentException("Lazy objects definitions collection must be traversable.");
36
        }
37
38
        foreach ($definitions as $definition) {
39
            if (!$definition instanceof Definition) {
40
                throw new InvalidArgumentException("Lazy object definition must be an instance of Isolate\\LazyObjects\\Proxy\\Definition");
41
            }
42
43
            $this->definitions[] = $definition;
44
        }
45
46
        $this->factory = $factory;
47
    }
48
49
    /**
50
     * @param $object
51
     * @return bool
52
     * 
53
     * @api
54
     */
55
    public function canWrap($object)
56
    {
57
        foreach ($this->definitions as $proxyDefinition) {
58
            if ($proxyDefinition->describeProxyFor($object)) {
59
                return true;
60
            }
61
        }
62
63
        return false;
64
    }
65
66
    /**
67
     * @param $object
68
     * @return WrappedObject
69
     * @throws RuntimeException
70
     * 
71
     * @api
72
     */
73
    public function wrap($object)
74
    {
75
        foreach ($this->definitions as $proxyDefinition) {
76
            if ($proxyDefinition->describeProxyFor($object)) {
77
                return $this->factory->createProxy($object, $proxyDefinition);
78
            }
79
        }
80
81
        throw new RuntimeException("Can\"t wrap objects that does\"t fit any proxy definition.");
82
    }
83
}
84