diff --git a/moodle/Tests/Util/TokenUtilTest.php b/moodle/Tests/Util/TokenUtilTest.php index 9f44094..eba6d3c 100644 --- a/moodle/Tests/Util/TokenUtilTest.php +++ b/moodle/Tests/Util/TokenUtilTest.php @@ -38,9 +38,9 @@ class TokenUtilTest extends MoodleCSBaseTestCase */ public function testGetObjectProperties( string $content, - int $type, - string $expectedType, - string $expectedName + $type, + ?string $expectedType, + ?string $expectedName ): void { $config = new Config([]); $ruleset = new Ruleset($config); @@ -90,6 +90,25 @@ public static function objectPropertiesProvider(): array { 'function', 'exampleFunction', ], + 'Unnamed anonymous class' => [ + << [ + '= 0) { @@ -161,4 +180,17 @@ public static function countGlobalScopesInFileProvider(): array { return $cases; } + + public function testObjectPropertiesInvalidPointer(): void { + $config = new Config([]); + $ruleset = new Ruleset($config); + + $phpcsFile = new DummyFile('process(); + + $stackPtr = 1000; + + $this->assertEquals('', TokenUtil::getObjectType($phpcsFile, $stackPtr)); + $this->assertEquals('', TokenUtil::getObjectName($phpcsFile, $stackPtr)); + } } diff --git a/moodle/Util/TokenUtil.php b/moodle/Util/TokenUtil.php index 07c13ce..21208b0 100644 --- a/moodle/Util/TokenUtil.php +++ b/moodle/Util/TokenUtil.php @@ -35,6 +35,11 @@ public static function getObjectType( int $stackPtr ): string { $tokens = $phpcsFile->getTokens(); + + if (!isset($tokens[$stackPtr])) { + return ''; + } + if ($tokens[$stackPtr]['code'] === T_OPEN_TAG) { return 'file'; } @@ -46,17 +51,29 @@ public static function getObjectType( * * @param File $phpcsFile * @param int $stackPtr - * @return string + * @return null|string */ public static function getObjectName( File $phpcsFile, int $stackPtr - ): string { + ): ?string { $tokens = $phpcsFile->getTokens(); + if (!isset($tokens[$stackPtr])) { + return ''; + } + if ($tokens[$stackPtr]['code'] === T_OPEN_TAG) { return basename($phpcsFile->getFilename()); } + if ($tokens[$stackPtr]['code'] === T_ANON_CLASS) { + return 'anonymous class'; + } + + if ($tokens[$stackPtr]['code'] === T_CLOSURE) { + return 'closure'; + } + return ObjectDeclarations::getName($phpcsFile, $stackPtr); }