Skip to content

Commit

Permalink
BCTokens: polyfill the tokenName() method
Browse files Browse the repository at this point in the history
This PHPCS method was introduced in PHPCS 3.0.0.

Includes unit tests.

Co-authored-by: Greg Sherwood <gsherwood@squiz.net>
  • Loading branch information
jrfnl and gsherwood committed May 12, 2021
1 parent bf8c4d2 commit 183274c
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
26 changes: 26 additions & 0 deletions PHPCSUtils/BackCompat/BCTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
71 changes: 71 additions & 0 deletions Tests/BackCompat/BCTokens/TokenNameTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php
/**
* PHPCSUtils, utility functions and classes for PHP_CodeSniffer sniff developers.
*
* @package PHPCSUtils
* @copyright 2019-2020 PHPCSUtils Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCSStandards/PHPCSUtils
*/

namespace PHPCSUtils\Tests\BackCompat\BCTokens;

use PHPCSUtils\BackCompat\BCTokens;
use PHPUnit\Framework\TestCase;

/**
* Test class.
*
* @covers \PHPCSUtils\BackCompat\BCTokens::tokenName
*
* @group tokens
*
* @since 1.0.0
*/
class TokenNameTest extends TestCase
{

/**
* Test the method.
*
* @dataProvider dataTokenName
*
* @param int|string $tokenCode The PHP/PHPCS token code to get the name for.
* @param string $expected The expected token name.
*
* @return void
*/
public function testTokenName($tokenCode, $expected)
{
$this->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',
],
];
}
}

0 comments on commit 183274c

Please sign in to comment.