Completed
Push — 2.x ( c48035...86395f )
by Akihito
14s queued 10s
created

NewInstance::weaveAspects()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\Di;
6
7
use Ray\Aop\Bind as AopBind;
8
9
final class NewInstance
10
{
11
    /**
12
     * @var string
13
     */
14
    private $class;
15
16
    /**
17
     * @var SetterMethods
18
     */
19
    private $setterMethods;
20
21
    /**
22
     * @var null|Arguments
23
     */
24
    private $arguments;
25
26
    /**
27
     * @var AspectBind
28
     */
29
    private $bind;
30
31 70
    public function __construct(
32
        \ReflectionClass $class,
33
        SetterMethods $setterMethods,
34
        Name $constructorName = null
35
    ) {
36 70
        $constructorName = $constructorName ?: new Name(Name::ANY);
37 70
        $this->class = $class->name;
38 70
        $constructor = $class->getConstructor();
39 70
        if ($constructor) {
40 59
            $this->arguments = new Arguments($constructor, $constructorName);
41
        }
42 70
        $this->setterMethods = $setterMethods;
43 70
    }
44
45
    /**
46
     * @throws \ReflectionException
47
     */
48 58
    public function __invoke(Container $container)
49
    {
50
        $instance = $this->arguments instanceof Arguments ? (new \ReflectionClass($this->class))->newInstanceArgs($this->arguments->inject($container)) : new $this->class;
51 58
52
        return $this->postNewInstance($container, $instance);
53
    }
54 57
55
    /**
56
     * @return string
57 57
     */
58 12
    public function __toString()
59
    {
60
        return $this->class;
61 57
    }
62
63
    /**
64
     * @throws \ReflectionException
65
     */
66
    public function newInstanceArgs(Container $container, array $params)
67 42
    {
68
        $instance = (new \ReflectionClass($this->class))->newInstanceArgs($params);
69 42
70
        return $this->postNewInstance($container, $instance);
71
    }
72
73
    /**
74
     * @param string $class
75 12
     */
76
    public function weaveAspects($class, AopBind $bind)
77 12
    {
78 12
        $this->class = $class;
79 12
        $this->bind = new AspectBind($bind);
80
    }
81
82
    private function postNewInstance(Container $container, $instance)
83
    {
84
        // setter injection
85
        ($this->setterMethods)($instance, $container);
86
87
        // bind dependency injected interceptors
88
        if ($this->bind instanceof AspectBind) {
89
            $instance->bindings = $this->bind->inject($container);
90
        }
91
92
        return $instance;
93
    }
94
}
95