Skip to content

Commit

Permalink
Object names may not be present for all objects (moodlehq#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewnicols committed Apr 2, 2024
1 parent 95d2abd commit b95a7a8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 5 deletions.
38 changes: 35 additions & 3 deletions moodle/Tests/Util/TokenUtilTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -90,6 +90,25 @@ public static function objectPropertiesProvider(): array {
'function',
'exampleFunction',
],
'Unnamed anonymous class' => [
<<<EOF
<?php
return new class extends phpunit_coverage_info {
/** @var array The list of folders relative to the plugin root to include in coverage generation. */
protected \$includelistfolders = ['classes'];
};
EOF,
T_ANON_CLASS,
'class',
'anonymous class',
],
'Unnamed closure' => [
'<?php $fn = function() {};',
T_CLOSURE,
'function',
'closure',
],
];

if (version_compare(PHP_VERSION, '8.1.0') >= 0) {
Expand Down Expand Up @@ -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('<?php', $ruleset, $config);
$phpcsFile->process();

$stackPtr = 1000;

$this->assertEquals('', TokenUtil::getObjectType($phpcsFile, $stackPtr));
$this->assertEquals('', TokenUtil::getObjectName($phpcsFile, $stackPtr));
}
}
21 changes: 19 additions & 2 deletions moodle/Util/TokenUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
}
Expand All @@ -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);
}

Expand Down

0 comments on commit b95a7a8

Please sign in to comment.