-
Notifications
You must be signed in to change notification settings - Fork 0
/
AliasExpander.php
387 lines (306 loc) · 8.37 KB
/
AliasExpander.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
<?php
namespace Milo;
/**
* Tool for a run-time class alias expanding (emulates the ::class from PHP 5.5)
* and a helper for annotations processing.
*
* You can choose one of four licences:
*
* @licence New BSD License
* @licence GNU General Public License version 2
* @licence GNU General Public License version 3
* @licence MIT License
*
* @version $Format:%h$
* @see https://github.com/milo/alias-expander
*
* @author Miloslav Hůla (https://github.com/milo)
*/
class AliasExpander
{
/** @var string cache dir path */
private $cacheDir;
/** @var array cache of aliases */
private $cache;
/** @var bool|int */
private $checkSeverity = FALSE;
/** @var bool */
private $checkAutoload = TRUE;
/**
* Sets cache dir.
* @param string path to cache directory
* @return self
*/
public function setCacheDir($dir)
{
$dir = $dir . DIRECTORY_SEPARATOR . 'AliasExpander';
$valid = TRUE;
if (!is_dir($dir)) {
set_error_handler(function($severity, $message) use ($dir, &$valid) {
restore_error_handler();
return $valid = is_dir($dir);
});
mkdir($dir);
restore_error_handler();
}
if ($valid) {
$this->cacheDir = $dir;
}
return $this;
}
/**
* Check if the class expanded from the alias has been defined.
* @param bool|int FALSE = off, TRUE = RuntimeException, int = user error level (E_USER_NOTICE, ...)
* @param bool allow autoload when checking existency
* @return self
*/
public function setExistsCheck($check, $autoload = TRUE)
{
$this->checkSeverity = $check;
$this->checkAutoload = (bool) $autoload;
return $this;
}
/**
* Expands class alias in a context where this method is called.
* @param string class alias
* @param int how deep is wrapped this method call
* @return string fully qualified class name
* @throws \RuntimeException when origin of call cannot be found in backtrace
* @throws \LogicException when empty alias name passed
*/
public function expand($alias, $depth = 0)
{
$bt = PHP_VERSION_ID < 50400
? debug_backtrace(FALSE)
: debug_backtrace(FALSE, $depth + 1);
if (!isset($bt[$depth]['file'], $bt[$depth]['line'])) {
throw new \RuntimeException('Cannot find an origin of call in backtrace.');
}
return $this->expandExplicit($alias, $bt[$depth]['file'], $bt[$depth]['line']);
}
/**
* Expands class alias in a file:line context.
* @param string class alias
* @param string file path
* @param int line number
* @return string fully qualified class name
* @throws \LogicException when empty class alias name passed
*/
public function expandExplicit($name, $file, $line = 0)
{
if (empty($name)) {
throw new \LogicException('Alias name must not be empty.');
}
if ($name[0] === '\\') { // already fully qualified
$return = ltrim($name, '\\');
} else {
if (($pos = strpos($name, '\\')) === FALSE) {
$lower = strtolower($name);
$suffix = '';
} else {
$lower = strtolower(substr($name, 0, $pos));
$suffix = substr($name, $pos);
}
if (($namespaces = $this->load($file)) === NULL) {
$namespaces = $this->parse(file_get_contents($file));
$this->store($file, $namespaces);
}
$next = each($namespaces);
do {
list(, $uses) = $next;
$next = each($namespaces);
} while ($next && $next[0] < $line);
if (isset($uses['aliases'][$lower]) && $uses['aliases'][$lower]['line'] < $line) {
$return = $uses['aliases'][$lower]['class'] . $suffix;
} else {
$return = $uses['namespace'] === '' ? $name : $uses['namespace'] . '\\' . $name;
}
}
if (!empty($this->checkSeverity) && !class_exists($return, $this->checkAutoload)) {
$message = "Class $return not found";
if (is_int($this->checkSeverity)) {
trigger_error($message, $this->checkSeverity);
} else {
throw new \RuntimeException($message);
}
}
return $return;
}
/**
* Parses PHP code and searches for namespaces and class aliases.
* <code>
* Return value:
*
* array(
* line => array(
* 'namespace' => string,
* 'aliases' => array(
* alias => array(
* 'line' => int,
* 'class' => string,
* )
* )
* )
* )
* </code>
* @param string PHP code
* @return array
*/
final protected function parse($code)
{
$tokens = @token_get_all($code); // @ - suppress useless warnings
$careTraits = PHP_VERSION_ID >= 50400;
$namespaces = array(
0 => array(
'namespace' => '',
'aliases' => array(),
),
);
$current = & $namespaces[0];
$namespace = $line = $class = $alias = $blockCounter = NULL;
foreach ($tokens as $token) {
if ($token[0] === T_WHITESPACE) {
// speed-up
} elseif ($token[0] === T_NAMESPACE) {
$namespace = '';
$line = $token[2];
} elseif ($namespace !== NULL && ($token[0] === T_STRING || $token[0] === T_NS_SEPARATOR)) {
$namespace .= $token[1];
} elseif ($namespace !== NULL && ($token === ';' || $token === '{')) {
$namespaces[$line] = array(
'namespace' => $namespace,
'aliases' => array(),
);
$current = & $namespaces[$line];
$namespace = NULL;
} elseif ($careTraits && ($token[0] === T_CLASS || $token[0] === T_TRAIT)) {
$blockCounter = 0;
} elseif ($blockCounter !== NULL) {
if ($token === '{') {
$blockCounter++;
} elseif ($token === '}') {
$blockCounter--;
if ($blockCounter === 0) {
$blockCounter = NULL;
}
}
// skipping Class/Trait body there
} elseif ($token[0] === T_USE) {
$alias = '';
$line = $token[2];
} elseif ($alias !== NULL) {
if ($token === '(' || $token[0] === T_FUNCTION || $token[0] === T_CONST) { // Cases of 'function() use() {}', or 'use function ...', or 'use const ...'
$class = $alias = NULL;
} elseif ($token[0] === T_STRING || $token[0] === T_NS_SEPARATOR) {
$alias .= $token[1];
} elseif ($token[0] === T_AS) {
$class = $alias;
$alias = '';
} elseif ($token === ';' || $token === ',') {
if ($class === NULL) {
$class = $alias;
$tmp = explode('\\', $alias);
$alias = end($tmp);
}
$current['aliases'][strtolower($alias)] = array('line' => $line, 'class' => ltrim($class, '\\'));
$class = NULL;
$alias = $token === ';' ? NULL : '';
}
}
}
return $namespaces;
}
/**
* Loads data from cache.
* @param string
* @return mixed
*/
protected function load($file)
{
if (isset($this->cache[$file])) {
return $this->cache[$file];
}
if ($this->cacheDir !== NULL
&& is_file($cacheFile = $this->cacheFileFor($file))
&& filemtime($file) < filemtime($cacheFile)
) {
if (($fd = fopen($cacheFile, 'r')) === FALSE || flock($fd, LOCK_SH) === FALSE) {
return NULL;
}
$cached = require $cacheFile;
flock($fd, LOCK_UN);
fclose($fd);
return $this->cache[$file] = $cached;
}
return NULL;
}
/**
* Store data to cache.
* @param string path to parsed PHP file
* @param mixed
* @return self
*/
protected function store($file, $data)
{
$this->cache[$file] = $data;
if ($this->cacheDir !== NULL) {
file_put_contents(
$this->cacheFileFor($file),
"<?php // AliasExpander cache for $file\n\nreturn " . var_export($data, TRUE) . ";\n",
LOCK_EX
);
}
return $this;
}
/**
* @param string path to parsed PHP file
* @return string
*/
private function cacheFileFor($file)
{
return $this->cacheDir
. DIRECTORY_SEPARATOR
. substr(sha1($file), 0, 5) . '-' . pathinfo($file, PATHINFO_FILENAME) . '.php';
}
}
/**
* A wrapper for the Milo\AliasExpander.
*
* @author Miloslav Hůla (https://github.com/milo)
*/
class Alias
{
/** @var AliasExpander */
private static $instance;
/**
* @throws \LogicException when instantized
*/
final public function __construct()
{
throw new \LogicException('This is a static class and cannot be instantized.');
}
/**
* @return AliasExpander
*/
public static function getExpander()
{
if (self::$instance === NULL) {
self::$instance = new AliasExpander;
}
return self::$instance;
}
/**
* {@link AliasExpander::expand()}
*/
public static function expand($alias, $depth = 0)
{
return self::getExpander()->expand($alias, $depth + 1);
}
/**
* {@link AliasExpander::expandExplicit()}
*/
public static function expandExplicit($alias, $file, $line = 0)
{
return self::getExpander()->expandExplicit($alias, $file, $line);
}
}