/
ModifierParser.php
258 lines (227 loc) · 7.71 KB
/
ModifierParser.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
<?php declare(strict_types = 1);
namespace Nextras\Orm\Entity\Reflection;
use Nette\Tokenizer\Exception;
use Nette\Tokenizer\Stream;
use Nette\Tokenizer\Token;
use Nette\Tokenizer\Tokenizer;
use Nette\Utils\Reflection;
use Nextras\Orm\Exception\InvalidStateException;
use ReflectionClass;
class ModifierParser
{
private const TOKEN_KEYWORD = 1;
private const TOKEN_STRING = 2;
private const TOKEN_LBRACKET = 3;
private const TOKEN_RBRACKET = 4;
private const TOKEN_EQUAL = 5;
private const TOKEN_SEPARATOR = 6;
private const TOKEN_WHITESPACE = 7;
/** @const regular expression for single & double quoted PHP string */
private const RE_STRING = '\'(?:\\\\.|[^\'\\\\])*\'|"(?:\\\\.|[^"\\\\])*"';
/** @var Tokenizer */
private $tokenizer;
public function __construct()
{
$this->tokenizer = new Tokenizer([
self::TOKEN_STRING => self::RE_STRING,
self::TOKEN_LBRACKET => '\[',
self::TOKEN_RBRACKET => '\]',
self::TOKEN_EQUAL => '=',
self::TOKEN_KEYWORD => '[a-zA-Z0-9_:$.*>\\\\-]+',
self::TOKEN_SEPARATOR => ',',
self::TOKEN_WHITESPACE => '\s+',
]);
}
/**
* @return string[]
* @phpstan-return list<string>
*/
public function matchModifiers(string $input): array
{
preg_match_all('#
\{(
(?:
' . self::RE_STRING . ' |
[^}]
)++
)\}#x', $input, $matches);
return $matches[1];
}
/**
* @phpstan-param ReflectionClass<object> $reflectionClass
* @phpstan-return array{string, array<int|string, mixed>}
* @throws InvalidModifierDefinitionException
*/
public function parse(string $string, ReflectionClass $reflectionClass): array
{
$iterator = $this->lex($string);
return [
$name = $this->processName($iterator),
$this->processArgs($iterator, $reflectionClass, $name, false),
];
}
private function lex(string $input): Stream
{
try {
$tokens = $this->tokenizer->tokenize($input)->tokens;
} catch (Exception $e) {
throw new InvalidModifierDefinitionException('Unable to tokenize the modifier.', 0, $e);
}
$tokens = array_filter($tokens, function ($token): bool {
return $token->type !== self::TOKEN_WHITESPACE;
});
$tokens = array_values($tokens);
return new Stream($tokens);
}
private function processName(Stream $iterator): string
{
$iterator->position++;
$currentToken = $iterator->currentToken();
if ($currentToken === null) {
throw new InvalidModifierDefinitionException("Modifier does not have a name.");
}
if ($currentToken->type !== self::TOKEN_KEYWORD) {
throw new InvalidModifierDefinitionException("Modifier does not have a name.");
} elseif (isset($iterator->tokens[$iterator->position + 1])) {
$nextToken = $iterator->tokens[$iterator->position + 1];
if ($nextToken->type === self::TOKEN_SEPARATOR) {
throw new InvalidModifierDefinitionException("After the {{$currentToken->value}}'s modifier name cannot be a comma separator.");
}
}
return $currentToken->value;
}
/**
* @phpstan-param ReflectionClass<object> $reflectionClass
* @phpstan-return array<int|string, mixed>
*/
private function processArgs(
Stream $iterator,
ReflectionClass $reflectionClass,
string $modifierName,
bool $inArray
): array
{
$result = [];
while (($currentToken = $iterator->nextToken()) !== null) {
$type = $currentToken->type;
if ($type === self::TOKEN_RBRACKET) {
if ($inArray) {
return $result;
} else {
throw new InvalidModifierDefinitionException("Modifier {{$modifierName}} mismatches brackets.");
}
} elseif ($type === self::TOKEN_STRING || $type === self::TOKEN_KEYWORD) {
$iterator->position++;
$nextToken = $iterator->currentToken();
$nextTokenType = $nextToken !== null ? $nextToken->type : null;
if ($nextTokenType === self::TOKEN_EQUAL) {
$iterator->position++;
$nextToken = $iterator->currentToken();
$nextTokenType = $nextToken !== null ? $nextToken->type : null;
if ($nextTokenType === self::TOKEN_LBRACKET) {
$value = $this->processValue($currentToken, $reflectionClass);
assert(!is_array($value));
$result[$value] = $this->processArgs($iterator, $reflectionClass, $modifierName, true);
} elseif ($nextTokenType === self::TOKEN_STRING || $nextTokenType === self::TOKEN_KEYWORD) {
$value = $this->processValue($currentToken, $reflectionClass);
assert(!is_array($value));
assert($nextToken !== null);
$result[$value] = $this->processValue($nextToken, $reflectionClass);
} elseif ($nextTokenType !== null) {
throw new InvalidModifierDefinitionException("Modifier {{$modifierName}} has invalid token after =.");
}
} else {
$iterator->position--;
$value = $this->processValue($currentToken, $reflectionClass);
if (is_array($value)) {
foreach ($value as $subValue) {
$result[] = $subValue;
}
} else {
$result[] = $value;
}
}
} elseif ($type === self::TOKEN_LBRACKET) {
$result[] = $this->processArgs($iterator, $reflectionClass, $modifierName, true);
} else {
throw new InvalidModifierDefinitionException("Modifier {{$modifierName}} has invalid token, expected string, keyword, or array.");
}
$iterator->position++;
$currentToken2 = $iterator->currentToken();
$type = $currentToken2 !== null ? $currentToken2->type : null;
if ($type === self::TOKEN_RBRACKET && $inArray) {
return $result;
} elseif ($type !== null && $type !== self::TOKEN_SEPARATOR) {
throw new InvalidModifierDefinitionException("Modifier {{$modifierName}} misses argument separator.");
}
}
if ($inArray) {
throw new InvalidModifierDefinitionException("Modifier {{$modifierName}} has unclosed array argument.");
}
return $result;
}
/**
* @phpstan-param ReflectionClass<object> $reflectionClass
* @return mixed
*/
private function processValue(Token $token, ReflectionClass $reflectionClass)
{
if ($token->type === self::TOKEN_STRING) {
return stripslashes(substr($token->value, 1, -1));
} elseif ($token->type === self::TOKEN_KEYWORD) {
return $this->processKeyword($token->value, $reflectionClass);
} else {
throw new InvalidStateException();
}
}
/**
* @phpstan-param ReflectionClass<object> $reflectionClass
* @return mixed
*/
private function processKeyword(string $value, ReflectionClass $reflectionClass)
{
if (strcasecmp($value, 'true') === 0) {
return true;
} elseif (strcasecmp($value, 'false') === 0) {
return false;
} elseif (strcasecmp($value, 'null') === 0) {
return null;
} elseif (is_numeric($value)) {
return $value * 1;
} elseif (preg_match('#^[a-z0-9_\\\\]+::[a-z0-9_]*(\\*)?$#i', $value) === 1) {
[$className, $const] = explode('::', $value, 2);
if ($className === 'self' || $className === 'static') {
$reflection = $reflectionClass;
} else {
$className = Reflection::expandClassName($className, $reflectionClass);
assert(class_exists($className) || interface_exists($className));
$reflection = new ReflectionClass($className);
}
$enum = [];
$constants = $reflection->getConstants();
if (strpos($const, '*') !== false) {
$prefix = rtrim($const, '*');
$prefixLength = strlen($prefix);
$count = 0;
foreach ($constants as $name => $constantValue) {
if (substr($name, 0, $prefixLength) === $prefix) {
$enum[$constantValue] = $constantValue;
$count += 1;
}
}
if ($count === 0) {
throw new InvalidModifierDefinitionException("No constant matches {$reflection->name}::{$const} pattern.");
}
} else {
if (!array_key_exists($const, $constants)) {
throw new InvalidModifierDefinitionException("Constant {$reflection->name}::{$const} does not exist.");
}
$value = $reflection->getConstant($const);
$enum[$value] = $value;
}
return array_values($enum);
} else {
return $value;
}
}
}