Completed
Push — grapher ( 6c7433 )
by Akihito
01:47
created

NewInstance::newInstanceArgs()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
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
    public function __construct(
32
        \ReflectionClass $class,
33
        SetterMethods $setterMethods,
34
        Name $constructorName = null
35
    ) {
36
        $constructorName = $constructorName ?: new Name(Name::ANY);
37
        $this->class = $class->name;
38
        $constructor = $class->getConstructor();
39
        if ($constructor) {
40
            $this->arguments = new Arguments($constructor, $constructorName);
41
        }
42
        $this->setterMethods = $setterMethods;
43
    }
44
45
    /**
46
     * @throws \ReflectionException
47
     */
48
    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
52
        return $this->postNewInstance($container, $instance);
53
54
    }
55
56
    /**
57
     * @return string
58
     */
59
    public function __toString()
60
    {
61
        return $this->class;
62
    }
63
64
    /**
65
     * @throws \ReflectionException
66
     */
67
    public function newInstanceArgs(Container $container, array $params)
68
    {
69
        $instance = (new \ReflectionClass($this->class))->newInstanceArgs($params);
70
71
        return $this->postNewInstance($container, $instance);
72
    }
73
74
    /**
75
     * @param string $class
76
     */
77
    public function weaveAspects($class, AopBind $bind)
78
    {
79
        $this->class = $class;
80
        $this->bind = new AspectBind($bind);
81
    }
82
83
    private function postNewInstance(Container $container, $instance)
84
    {
85
        // setter injection
86
        ($this->setterMethods)( $instance, $container );
87
88
        // bind dependency injected interceptors
89
        if ($this->bind instanceof AspectBind) {
90
            $instance->bindings = $this->bind->inject( $container );
91
        }
92
93
        return $instance;
94
}
95
}
96