-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Inject.php
81 lines (72 loc) 路 2.4 KB
/
Inject.php
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
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Di\Annotation;
use Hyperf\Di\BetterReflectionManager;
use Hyperf\Di\Exception\AnnotationException;
use Hyperf\Di\TypesFinderManager;
use phpDocumentor\Reflection\Types\Object_;
/**
* @Annotation
* @Target({"PROPERTY"})
*/
class Inject extends AbstractAnnotation
{
/**
* @var string
*/
public $value;
/**
* @var bool
*/
public $required = true;
/**
* @var bool
*/
public $lazy = false;
public function __construct($value = null)
{
parent::__construct($value);
}
public function collectProperty(string $className, ?string $target): void
{
try {
$reflectionClass = BetterReflectionManager::reflectClass($className);
$properties = $reflectionClass->getImmediateProperties();
$reflectionProperty = $properties[$target] ?? null;
if (! $reflectionProperty) {
$this->value = '';
return;
}
if ($reflectionProperty->hasType()) {
$this->value = $reflectionProperty->getType()->getName();
} else {
$reflectionTypes = TypesFinderManager::getPropertyFinder()->__invoke($reflectionProperty, $reflectionClass->getDeclaringNamespaceAst());
if (isset($reflectionTypes[0]) && $reflectionTypes[0] instanceof Object_) {
$this->value = ltrim((string) $reflectionTypes[0], '\\');
}
}
if (empty($this->value)) {
throw new AnnotationException("The @Inject value is invalid for {$className}->{$target}");
}
if ($this->lazy) {
$this->value = 'HyperfLazy\\' . $this->value;
}
AnnotationCollector::collectProperty($className, $target, static::class, $this);
} catch (AnnotationException $exception) {
if ($this->required) {
throw $exception;
}
$this->value = '';
} catch (\Throwable $exception) {
throw new AnnotationException("The @Inject value is invalid for {$className}->{$target}. Because {$exception->getMessage()}");
}
}
}