Skip to content

Generic/ConstructorName: more defensive coding / prevent fatal error #814

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,13 @@ protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScop
$this->currentClass = $className;
}

$methodName = strtolower($phpcsFile->getDeclarationName($stackPtr));
$methodName = $phpcsFile->getDeclarationName($stackPtr);
if ($methodName === null) {
// Live coding or parse error. Bow out.
return;
}

$methodName = strtolower($methodName);
if ($methodName === $className) {
if (in_array('__construct', $this->functionList, true) === false) {
$error = 'PHP4 style constructors are not allowed; use "__construct()" instead';
Expand Down Expand Up @@ -164,7 +169,13 @@ protected function loadFunctionNamesInScope(File $phpcsFile, $currScope)
continue;
}

$this->functionList[] = trim(strtolower($phpcsFile->getDeclarationName($i)));
$methodName = $phpcsFile->getDeclarationName($i);
if ($methodName === null) {
// Live coding or parse error. Ignore.
continue;
}

$this->functionList[] = trim(strtolower($methodName));

if (isset($tokens[$i]['scope_closer']) !== false) {
// Skip past nested functions and such.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

// Intentional parse error (missing method name).
// This should be the only test in this file.
// Testing that the sniff is *not* triggered.

class My_Class {
public function {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,31 @@ final class ConstructorNameUnitTest extends AbstractSniffUnitTest
* The key of the array should represent the line number and the value
* should represent the number of errors that should occur on that line.
*
* @param string $testFile The name of the test file to process.
*
* @return array<int, int>
*/
public function getErrorList()
public function getErrorList($testFile='')
{
return [
6 => 1,
11 => 1,
47 => 1,
62 => 1,
91 => 1,
103 => 1,
104 => 1,
112 => 1,
120 => 1,
121 => 1,
126 => 1,
127 => 1,
];
switch ($testFile) {
case 'ConstructorNameUnitTest.1.inc':
return [
6 => 1,
11 => 1,
47 => 1,
62 => 1,
91 => 1,
103 => 1,
104 => 1,
112 => 1,
120 => 1,
121 => 1,
126 => 1,
127 => 1,
];
default:
return [];
}//end switch

}//end getErrorList()

Expand Down