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
|
70 |
|
) { |
36
|
|
|
$constructorName = $constructorName ?: new Name(Name::ANY); |
37
|
|
|
$this->class = $class->name; |
38
|
|
|
$constructor = $class->getConstructor(); |
39
|
|
|
if ($constructor) { |
40
|
70 |
|
$this->arguments = new Arguments($constructor, $constructorName); |
41
|
70 |
|
} |
42
|
70 |
|
$this->setterMethods = $setterMethods; |
43
|
70 |
|
} |
44
|
59 |
|
|
45
|
|
|
/** |
46
|
70 |
|
* @throws \ReflectionException |
47
|
70 |
|
*/ |
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
|
58 |
|
|
55
|
|
|
/** |
56
|
|
|
* @return string |
57
|
58 |
|
*/ |
58
|
|
|
public function __toString() |
59
|
|
|
{ |
60
|
57 |
|
return $this->class; |
61
|
|
|
} |
62
|
|
|
|
63
|
57 |
|
/** |
64
|
12 |
|
* @throws \ReflectionException |
65
|
|
|
*/ |
66
|
|
|
public function newInstanceArgs(Container $container, array $params) |
67
|
57 |
|
{ |
68
|
|
|
$instance = (new \ReflectionClass($this->class))->newInstanceArgs($params); |
69
|
|
|
|
70
|
|
|
return $this->postNewInstance($container, $instance); |
71
|
|
|
} |
72
|
|
|
|
73
|
42 |
|
/** |
74
|
|
|
* @param string $class |
75
|
42 |
|
*/ |
76
|
|
|
public function weaveAspects($class, AopBind $bind) |
77
|
|
|
{ |
78
|
|
|
$this->class = $class; |
79
|
|
|
$this->bind = new AspectBind($bind); |
80
|
|
|
} |
81
|
|
|
|
82
|
12 |
|
private function postNewInstance(Container $container, $instance) |
83
|
|
|
{ |
84
|
12 |
|
// setter injection |
85
|
12 |
|
($this->setterMethods)($instance, $container); |
86
|
12 |
|
|
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
|
|
|
|