Skip to content

Commit

Permalink
PEAR/Functions/FunctionDeclaration: add extra defensive coding
Browse files Browse the repository at this point in the history
When the sniff is run during live coding, the sniff could encounter a situation where a function declaration does not have a scope opener, not a function body.

In that case, the "SpaceBeforeSemicolon" check would try to find a semi-colon, presuming the function is an abstract method or interface method, but would not find one, which would result in the `if ($tokens[($end - 1)]['content'] === $phpcsFile->eolChar)` condition throwing a _"Undefined array key -1"_ notice.

Fixed now.

Includes test safeguarding the fix.

Note: this fix will, by extension, fix this same error for the `PSR2.Methods.FunctionCallSignature` sniff and the `Squiz.Functions.MultiLineFunctionDeclaration` sniff.

:point_right: this commit will be easier to review while ignoring whitespace changes.
  • Loading branch information
jrfnl committed Mar 29, 2024
1 parent 8135be1 commit d9cf33f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/Standards/PEAR/Sniffs/Functions/FunctionDeclarationSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,23 +128,25 @@ public function process(File $phpcsFile, $stackPtr)
// Must be no space before semicolon in abstract/interface methods.
if ($methodProps['has_body'] === false) {
$end = $phpcsFile->findNext(T_SEMICOLON, $closeBracket);
if ($tokens[($end - 1)]['content'] === $phpcsFile->eolChar) {
$spaces = 'newline';
} else if ($tokens[($end - 1)]['code'] === T_WHITESPACE) {
$spaces = $tokens[($end - 1)]['length'];
} else {
$spaces = 0;
}
if ($end !== false) {
if ($tokens[($end - 1)]['content'] === $phpcsFile->eolChar) {
$spaces = 'newline';
} else if ($tokens[($end - 1)]['code'] === T_WHITESPACE) {
$spaces = $tokens[($end - 1)]['length'];
} else {
$spaces = 0;
}

if ($spaces !== 0) {
$error = 'Expected 0 spaces before semicolon; %s found';
$data = [$spaces];
$fix = $phpcsFile->addFixableError($error, $end, 'SpaceBeforeSemicolon', $data);
if ($fix === true) {
$phpcsFile->fixer->replaceToken(($end - 1), '');
if ($spaces !== 0) {
$error = 'Expected 0 spaces before semicolon; %s found';
$data = [$spaces];
$fix = $phpcsFile->addFixableError($error, $end, 'SpaceBeforeSemicolon', $data);
if ($fix === true) {
$phpcsFile->fixer->replaceToken(($end - 1), '');
}
}
}
}
}//end if
}//end if

// Must be one space before and after USE keyword for closures.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

// Intentional parse error/live coding test.
// This must be the only test in this file.
// Safeguarding that the sniff does not throw a PHP notice for this test.

function liveCoding()

0 comments on commit d9cf33f

Please sign in to comment.