Skip to content

Commit 099d0b1

Browse files
authored
Merge pull request microsoft#187 from TysonAndre/speed-up-token
Speed up token value to name lookup
2 parents fc98829 + b98ede7 commit 099d0b1

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

src/Token.php

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,25 @@ public function getEndPosition() {
5959
return $this->fullStart + $this->length;
6060
}
6161

62-
public static function getTokenKindNameFromValue($kindName) {
63-
$constants = (new \ReflectionClass("Microsoft\\PhpParser\\TokenKind"))->getConstants();
64-
foreach ($constants as $name => $val) {
65-
if ($val == $kindName) {
66-
$kindName = $name;
67-
break;
68-
}
62+
/**
63+
* @return string[] - A hash map of the format [int $tokenKind => string $tokenName]
64+
*/
65+
private static function getTokenKindNameFromValueMap() {
66+
static $mapToKindName;
67+
if ($mapToKindName === null) {
68+
$constants = (new \ReflectionClass("Microsoft\\PhpParser\\TokenKind"))->getConstants();
69+
$mapToKindName = \array_flip($constants);
6970
}
70-
return $kindName;
71+
return $mapToKindName;
72+
}
73+
74+
/**
75+
* @param int $kind
76+
* @return string (Or int, if the kind name for $kind wasn't found)
77+
*/
78+
public static function getTokenKindNameFromValue($kind) {
79+
$mapToKindName = self::getTokenKindNameFromValueMap();
80+
return $mapToKindName[$kind] ?? $kind;
7181
}
7282

7383
public function jsonSerialize() {

0 commit comments

Comments
 (0)