Skip to content

Commit 3a76062

Browse files
committed
Generic/ConstructorName: more defensive coding
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 test safeguarding the fix.
1 parent 90e3190 commit 3a76062

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,13 @@ protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScop
7878
$this->currentClass = $className;
7979
}
8080

81-
$methodName = strtolower($phpcsFile->getDeclarationName($stackPtr));
81+
$methodName = $phpcsFile->getDeclarationName($stackPtr);
82+
if ($methodName === null) {
83+
// Live coding or parse error. Bow out.
84+
return;
85+
}
8286

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

167-
$this->functionList[] = trim(strtolower($phpcsFile->getDeclarationName($i)));
172+
$methodName = $phpcsFile->getDeclarationName($i);
173+
if ($methodName === null) {
174+
// Live coding or parse error. Ignore.
175+
continue;
176+
}
177+
178+
$this->functionList[] = trim(strtolower($methodName));
168179

169180
if (isset($tokens[$i]['scope_closer']) !== false) {
170181
// Skip past nested functions and such.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
// Intentional parse error (missing method name).
4+
// This should be the only test in this file.
5+
// Testing that the sniff is *not* triggered.
6+
7+
class My_Class {
8+
public function {}
9+
}

0 commit comments

Comments
 (0)