Skip to content

Commit

Permalink
Generic/ConstructorName: more defensive coding
Browse files Browse the repository at this point in the history
This sniff could throw the following fatal errors when it encountered parse errors/during live coding:

```
Fatal error: Uncaught PHP_CodeSniffer\Exceptions\RuntimeException: strtolower(): Passing null to parameter #1 ($string) of type string is deprecated in path/to/PHPCS/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php on line 83 in path/to/PHPCS/src/Runner.php on line 624

Fatal error: Uncaught PHP_CodeSniffer\Exceptions\RuntimeException: strtolower(): Passing null to parameter #1 ($string) of type string is deprecated in path/to/PHPCS/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php on line 167 in path/to/PHPCS/src/Runner.php on line 624
```

Fixed now by adding more defensive coding.

Includes tests safeguarding the fix.
  • Loading branch information
jrfnl committed Feb 12, 2025
1 parent 16a5319 commit f7e0548
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
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
@@ -0,0 +1,7 @@
<?php

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

function

0 comments on commit f7e0548

Please sign in to comment.