slevomat / coding-standard

Slevomat Coding Standard for PHP_CodeSniffer provides many useful sniffs
MIT License
1.37k stars 170 forks source link

SlevomatCodingStandard.PHP.UselessParentheses.UselessParentheses false positive producing invalid syntax #1672

Open whitefang57 opened 2 months ago

whitefang57 commented 2 months ago

Using the following example:

<?php

declare(strict_types=1);

$foo = false;
$fn  = static fn () => ', World!';

echo 'Hello' . ($foo ? ' There' : $fn());
echo "\n";
echo 'Hello' . ($foo) ? ' There' : $fn();
echo "\n";
echo 'Hello' . (($foo) ? ' There' : $fn());
echo "\n";

Running phpcs using the Doctrine Coding Standard against this file produces the following:

$ phpcs --standard=Doctrine test.php

----------------------------------------------------------------------
FOUND 3 ERRORS AFFECTING 2 LINES
----------------------------------------------------------------------
 10 | ERROR | [x] Useless parentheses.
 12 | ERROR | [x] Useless parentheses.
 12 | ERROR | [x] Useless parentheses.
----------------------------------------------------------------------

As you can see, the first block was not flagged as violating the standard while the second and third were.

phpcbf modifies the file in the following way:

<?php

declare(strict_types=1);

$foo = false;
$fn  = static fn () => ', World!';

echo 'Hello' . ($foo ? ' There' : $fn());
echo "\n";
echo 'Hello' . $foo ? ' There' : $fn();
echo "\n";
echo 'Hello' . $foo ? ' There' : $fn();
echo "\n";

Which does not make it syntactically invalid, but does drastically change the meaning of the code.

Before running phpcbf it outputs:

Hello, World!
 There
Hello, World!

After running phpcbf it outputs:

Hello, World!
 There
 There