Skip to content

Commit a4c3a5f

Browse files
authored
Fix aliased trait method (#9)
1 parent 41d19aa commit a4c3a5f

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/UsedSymbolExtractor.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,17 @@
1212
use function token_get_all;
1313
use const PHP_VERSION_ID;
1414
use const T_AS;
15+
use const T_CLASS;
1516
use const T_COMMENT;
1617
use const T_DOC_COMMENT;
18+
use const T_ENUM;
19+
use const T_INTERFACE;
1720
use const T_NAME_FULLY_QUALIFIED;
1821
use const T_NAME_QUALIFIED;
1922
use const T_NAMESPACE;
2023
use const T_NS_SEPARATOR;
2124
use const T_STRING;
25+
use const T_TRAIT;
2226
use const T_USE;
2327
use const T_WHITESPACE;
2428

@@ -40,6 +44,18 @@ class UsedSymbolExtractor
4044
*/
4145
private $pointer = 0;
4246

47+
/**
48+
* When not null, we are inside class-like and use statements dont need to be parsed
49+
*
50+
* @var int|null
51+
*/
52+
private $inClassLevel = null;
53+
54+
/**
55+
* @var int
56+
*/
57+
private $level = 0;
58+
4359
public function __construct(string $code)
4460
{
4561
$this->tokens = token_get_all($code);
@@ -149,6 +165,20 @@ private function getNextEffectiveToken()
149165
continue;
150166
}
151167

168+
if ($token[0] === T_CLASS || $token[0] === T_INTERFACE || $token[0] === T_TRAIT || (PHP_VERSION_ID >= 80100 && $token[0] === T_ENUM)) {
169+
$this->inClassLevel = $this->level + 1;
170+
}
171+
172+
if ($token === '{') {
173+
$this->level++;
174+
} elseif ($token === '}') {
175+
if ($this->level === $this->inClassLevel) {
176+
$this->inClassLevel = null;
177+
}
178+
179+
$this->level--;
180+
}
181+
152182
return $token;
153183
}
154184

@@ -198,6 +228,10 @@ private function parseNameForOldPhp(): string
198228
*/
199229
public function parseUseStatement(): ?array
200230
{
231+
if ($this->inClassLevel !== null) {
232+
return null;
233+
}
234+
201235
$groupRoot = '';
202236
$class = '';
203237
$alias = '';

tests/data/used-symbols/use-statements.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,18 @@
1717
new DirectoryExists();
1818
new FileExists();
1919

20+
trait Trait_ {
21+
public function originalMethod(): void {}
22+
}
23+
24+
class Class_
25+
{
26+
use Trait_ {
27+
originalMethod as newMethodName;
28+
}
29+
30+
public function test() {
31+
$this->newMethodName();
32+
}
33+
34+
}

0 commit comments

Comments
 (0)