Skip to content

Commit 2048a01

Browse files
committed
Squiz/NonExecutableCode: bug fix - expressions in ternary
The `T_EXIT` token can be used in ternaries without affecting code after the ternary expression. See: https://3v4l.org/oMWuA#veol Fixed now. Includes unit test. Fixes 2857
1 parent 4c094ed commit 2048a01

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/Standards/Squiz/Sniffs/PHP/NonExecutableCodeSniff.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ public function process(File $phpcsFile, $stackPtr)
6868
if (isset(Tokens::$booleanOperators[$tokens[$prev]['code']]) === true) {
6969
return;
7070
}
71+
72+
// Expressions are allowed in the `else` clause of ternaries.
73+
if ($tokens[$prev]['code'] === T_INLINE_THEN || $tokens[$prev]['code'] === T_INLINE_ELSE) {
74+
return;
75+
}
7176
}
7277

7378
// Check if this token is actually part of a one-line IF or ELSE statement.

src/Standards/Squiz/Tests/PHP/NonExecutableCodeUnitTest.1.inc

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,5 +323,17 @@ function exitExpressionsWithLogicalOperators() {
323323
echo 'still executable as exit, in all of the above cases, is used as part of an expression';
324324
}
325325

326+
// Inline expressions are allowed in ternaries.
327+
function exitExpressionsInTernary() {
328+
$value = $myValue ? $myValue : exit();
329+
$value = $myValue ?: exit();
330+
$value = $var == 'foo' ? 'bar' : die( 'world' );
331+
332+
$value = (!$myValue ) ? exit() : $myValue;
333+
$value = $var != 'foo' ? die( 'world' ) : 'bar';
334+
335+
echo 'still executable';
336+
}
337+
326338
// Intentional syntax error.
327339
return array_map(

0 commit comments

Comments
 (0)