-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAnnotationReader.php
More file actions
68 lines (58 loc) · 1.91 KB
/
AnnotationReader.php
File metadata and controls
68 lines (58 loc) · 1.91 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
<?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\Constants;
use BackedEnum;
use Hyperf\Constants\Annotation\Message;
use Hyperf\Stringable\Str;
use ReflectionClassConstant;
class AnnotationReader
{
/**
* @param array<ReflectionClassConstant> $classConstants
*/
public function getAnnotations(array $classConstants): array
{
$result = [];
foreach ($classConstants as $classConstant) {
$code = $classConstant->getValue();
if ($classConstant->isEnumCase()) {
$code = $code instanceof BackedEnum ? $code->value : $code->name;
}
$docComment = $classConstant->getDocComment();
// Not support float and bool, because it will be convert to int.
if ($docComment && (is_int($code) || is_string($code))) {
$result[$code] = $this->parse($docComment, $result[$code] ?? []);
}
// Support PHP8 Attribute.
foreach ($classConstant->getAttributes() as $ref) {
$attribute = $ref->newInstance();
if ($attribute instanceof Message) {
$result[$code][$attribute->getLowerCaseKey()] = $attribute->value;
}
}
}
return $result;
}
protected function parse(string $doc, array $previous): array
{
$pattern = '/@(\w+)\("(.+)"\)/U';
if (preg_match_all($pattern, $doc, $result)) {
$keys = $result[1];
$values = $result[2];
foreach ($keys as $i => $key) {
if (isset($values[$i])) {
$previous[Str::lower($key)] = $values[$i];
}
}
}
return $previous;
}
}