-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathInteractsWithInject.php
More file actions
61 lines (54 loc) · 2.19 KB
/
InteractsWithInject.php
File metadata and controls
61 lines (54 loc) · 2.19 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
<?php
namespace think\annotation;
use ReflectionObject;
use think\App;
/**
* Trait InteractsWithInject
* @package think\annotation\traits
* @property App $app
*/
trait InteractsWithInject
{
protected function autoInject()
{
if ($this->app->config->get('annotation.inject.enable', true)) {
$this->app->resolving(function ($object, $app) {
if ($this->isInjectClass(get_class($object))) {
$refObject = new ReflectionObject($object);
foreach ($refObject->getProperties() as $refProperty) {
if ($refProperty->isDefault() && !$refProperty->isStatic()) {
$attrs = $refProperty->getAttributes(Inject::class);
if (!empty($attrs)) {
if (!empty($attrs[0]->getArguments()[0])) {
$type = $attrs[0]->getArguments()[0];
} elseif ($refProperty->getType() && !$refProperty->getType()->isBuiltin()) {
$type = $refProperty->getType()->getName();
}
if (isset($type)) {
$value = $app->make($type);
if (!$refProperty->isPublic()) {
$refProperty->setAccessible(true);
}
$refProperty->setValue($object, $value);
}
}
}
}
if ($refObject->hasMethod('__injected')) {
$app->invokeMethod([$object, '__injected']);
}
}
});
}
}
protected function isInjectClass($name)
{
$namespaces = ['app\\'] + $this->app->config->get('annotation.inject.namespaces', []);
foreach ($namespaces as $namespace) {
$namespace = rtrim($namespace, '\\') . '\\';
if (0 === stripos(rtrim($name, '\\') . '\\', $namespace)) {
return true;
}
}
}
}