Skip to content

Commit e2b1a9c

Browse files
committed
Avoid fixer conflict on parse error
Because PHP evaluates `false - 1` to `(int) -1`, the array look-up was looking for `$tokens[-1]` which does not exist. This code change avoids that case by detecting the parse error / live coding situation early. Includes test.
1 parent ee10b9f commit e2b1a9c

File tree

4 files changed

+18
-1
lines changed

4 files changed

+18
-1
lines changed

src/Standards/PSR12/Sniffs/Functions/ReturnTypeDeclarationSniff.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,12 @@ public function process(File $phpcsFile, int $stackPtr)
6161
$returnType = $phpcsFile->findPrevious(T_NULLABLE, ($returnType - 1));
6262
}
6363

64+
$colon = $phpcsFile->findPrevious(T_COLON, $returnType, $tokens[$stackPtr]['parenthesis_closer']);
65+
if ($colon === false) {
66+
// Parse error / live coding.
67+
return;
68+
}
69+
6470
if ($tokens[($returnType - 1)]['code'] !== T_WHITESPACE
6571
|| $tokens[($returnType - 1)]['content'] !== ' '
6672
|| $tokens[($returnType - 2)]['code'] !== T_COLON
@@ -83,7 +89,6 @@ public function process(File $phpcsFile, int $stackPtr)
8389
}
8490
}
8591

86-
$colon = $phpcsFile->findPrevious(T_COLON, $returnType);
8792
if ($tokens[($colon - 1)]['code'] !== T_CLOSE_PARENTHESIS) {
8893
$error = 'There must not be a space before the colon in a return type declaration';
8994
$prev = $phpcsFile->findPrevious(T_WHITESPACE, ($colon - 1), null, true);
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?php
2+
3+
// Intentional parse error. There should be a colon between the function parameters and its return type.
4+
$closure = function () null { return null; };
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?php
2+
3+
// Intentional parse error. There should be a colon between the function 'use' and its return type.
4+
$closure = function ($foo) use ($bar) string { return 'baz'; };
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?php
2+
3+
// Intentional parse error. There should be a colon between the function parameters and its return type.
4+
function foo($obj = new DateTime(datetime: "now")) null {}

0 commit comments

Comments
 (0)