-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInjector.php
More file actions
115 lines (103 loc) · 2.79 KB
/
Injector.php
File metadata and controls
115 lines (103 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
namespace WebStream\DI;
use PhpDocReader\PhpDocReader;
use WebStream\Container\Container;
use WebStream\Exception\Extend\AnnotationException;
/**
* Injector
* @author Ryuichi TANAKA.
* @since 2015/12/26
* @version 0.7
*/
trait Injector
{
/**
* @var Container プロパティコンテナ
*/
private Container $propertyContainer;
/**
* オブジェクトを注入する
* @param string プロパティ名
* @param mixed オブジェクト
* @return Injector
*/
public function inject(string $name, $object)
{
$this->{$name} = $object;
return $this;
}
/**
* 型指定されたオブジェクトを注入する
* @param string プロパティ名
* @param mixed オブジェクト
* @return Injector
* @throws WebStream\Exception\Extend\AnnotationException
*/
public function strictInject(string $name, $object)
{
$reader = new PhpDocReader();
try {
$refClass = new \ReflectionClass($this);
while ($refClass !== false) {
if ($refClass->hasProperty($name)) {
$refProperty = $refClass->getProperty($name);
$classpath = $reader->getPropertyClass($refProperty);
if ($object instanceof $classpath) {
$this->inject($name, $object);
} else {
throw new AnnotationException("The type of injected property must be instance of ${classpath}");
}
}
$refClass = $refClass->getParentClass();
}
} catch (\ReflectionException $e) {
throw new AnnotationException($e);
}
return $this;
}
/**
* overload setter
* @param mixed $name
* @param mixed $value
*/
public function __set($name, $value)
{
if (!isset($this->propertyContainer)) {
$this->propertyContainer = new Container(false);
}
$this->propertyContainer->{$name} = $value;
}
/**
* overload setter
* @param mixed $name
* @return mixed|null
*/
public function __get($name)
{
return $this->propertyContainer !== null ? $this->propertyContainer->{$name} : null;
}
/**
* overload isset
* @param mixed $name
* @return bool
*/
public function __isset($name)
{
return $this->propertyContainer === null || $this->propertyContainer->{$name} === null;
}
/**
* overload unset
* @param mixed $name
*/
public function __unset($name)
{
$this->propertyContainer->remove($name);
}
/**
* コンテナクリア
*/
public function __clear()
{
$this->propertyContainer = null;
}
}