1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Minime\Annotations; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* An Annotations parser |
7
|
|
|
* |
8
|
|
|
* @package Annotations |
9
|
|
|
* @author Márcio Almada and the Minime Community |
10
|
|
|
* @license MIT |
11
|
|
|
* |
12
|
|
|
*/ |
13
|
|
|
class Parser extends DynamicParser |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* The lexer table of parsable types in a given docblock |
17
|
|
|
* declared in a ['token' => 'symbol'] associative array |
18
|
|
|
* |
19
|
|
|
* @var array |
20
|
|
|
*/ |
21
|
|
|
protected $types = [ |
22
|
|
|
'\Minime\Annotations\Types\IntegerType' => 'integer', |
23
|
|
|
'\Minime\Annotations\Types\StringType' => 'string', |
24
|
|
|
'\Minime\Annotations\Types\FloatType' => 'float', |
25
|
|
|
'\Minime\Annotations\Types\JsonType' => 'json', |
26
|
|
|
'\Minime\Annotations\Types\ConcreteType' => '->' |
27
|
|
|
]; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* The regex equivalent of $types |
31
|
|
|
* |
32
|
|
|
* @var string |
33
|
|
|
*/ |
34
|
|
|
protected $typesPattern; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Parser constructor |
38
|
|
|
* |
39
|
|
|
*/ |
40
|
|
|
public function __construct() |
41
|
|
|
{ |
42
|
|
|
$this->buildTypesPattern(); |
43
|
|
|
parent::__construct(); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function registerType($class, $token) |
47
|
|
|
{ |
48
|
|
|
$this->types[$class] = $token; |
49
|
|
|
$this->buildTypesPattern(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function unregisterType($class) |
53
|
|
|
{ |
54
|
|
|
unset($this->types[$class]); |
55
|
|
|
$this->buildTypesPattern(); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Parse a single annotation value |
60
|
|
|
* |
61
|
|
|
* @param string $value |
62
|
|
|
* @param string $key |
63
|
|
|
* @return mixed |
64
|
|
|
*/ |
65
|
|
|
protected function parseValue($value, $key = null) |
66
|
|
|
{ |
67
|
|
|
$value = trim($value); |
68
|
|
|
$type = '\Minime\\Annotations\\Types\\DynamicType'; |
69
|
|
|
if (preg_match($this->typesPattern, $value, $found)) { // strong typed |
70
|
|
|
$type = $found[1]; |
71
|
|
|
$value = trim(substr($value, strlen($type))); |
72
|
|
|
if (in_array($type, $this->types)) { |
73
|
|
|
$type = array_search($type, $this->types); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return (new $type)->parse($value, $key); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Makes `@\My\Namespaced\Class` equivalent of `@My\Namespaced\Class` |
82
|
|
|
* |
83
|
|
|
* @param string $key |
84
|
|
|
* @return string |
85
|
|
|
*/ |
86
|
|
|
protected function sanitizeKey($key) |
87
|
|
|
{ |
88
|
|
|
if (0 === strpos($key, '\\')) { |
89
|
|
|
$key = substr($key, 1); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return $key; |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
protected function buildTypesPattern() |
96
|
|
|
{ |
97
|
|
|
$this->typesPattern = '/^('.implode('|', $this->types).')(\s+)/'; |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|