diff --git a/PHPCSUtils/BackCompat/BCTokens.php b/PHPCSUtils/BackCompat/BCTokens.php index 9b93015c..28e1c52a 100644 --- a/PHPCSUtils/BackCompat/BCTokens.php +++ b/PHPCSUtils/BackCompat/BCTokens.php @@ -460,4 +460,30 @@ public static function magicConstants() return Collections::$magicConstants; } + + /** + * Given a token, returns the name of the token. + * + * If passed an integer, the token name is sourced from PHP's token_name() + * function. If passed a string, it is assumed to be a PHPCS-supplied token + * that begins with PHPCS_T_, so the name is sourced from the token value itself. + * + * Changelog for the PHPCS native: + * - Introduced in PHPCS 3.0.0. + * + * @see \PHP_CodeSniffer\Util\Tokens::tokenName() Original function. + * + * @param int|string $token The token to get the name for. + * + * @return string + */ + public static function tokenName($token) + { + if (\is_string($token) === false) { + // PHP-supplied token name. + return \token_name($token); + } + + return \substr($token, 6); + } } diff --git a/Tests/BackCompat/BCTokens/TokenNameTest.php b/Tests/BackCompat/BCTokens/TokenNameTest.php new file mode 100644 index 00000000..08e25b61 --- /dev/null +++ b/Tests/BackCompat/BCTokens/TokenNameTest.php @@ -0,0 +1,71 @@ +assertSame($expected, BCTokens::tokenName($tokenCode)); + } + + /** + * Data provider. + * + * @see testTokenName() For the array format. + * + * @return array + */ + public function dataTokenName() + { + return [ + 'PHP native token: T_COMMA' => [ + \T_COMMA, + 'T_COMMA', + ], + 'PHP native token: T_SELF' => [ + \T_SELF, + 'T_SELF', + ], + 'PHPCS native token: T_CLOSURE' => [ + \T_CLOSURE, + 'T_CLOSURE', + ], + 'PHPCS native token: T_STRING_CONCAT' => [ + \T_STRING_CONCAT, + 'T_STRING_CONCAT', + ], + ]; + } +}