PHPCSStandards / PHP_CodeSniffer

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.
BSD 3-Clause "New" or "Revised" License
857 stars 53 forks source link

Generic/IncrementDecrementSpacing: inconsistent error message #288

Closed rodrigoprimo closed 7 months ago

rodrigoprimo commented 7 months ago

Describe the bug

I believe there is a minor inconsistency in two error messages displayed by the Generic.WhiteSpace.IncrementDecrementSpacing sniff. This sniff displays the following when it finds a newline between a pre-decrement and a variable:

Expected no spaces between the decrement operator and $i; newline found

But when it finds a newline between a variable and a post-decrement operator, the message is:

Expected no spaces between $i and the decrement operator; 0 found

Code sample

--
$i;

$i
--;

To reproduce

Steps to reproduce the behavior:

  1. Create a file called test.php with the code sample above.
  2. Run phpcs --standard=Generic --sniffs=Generic.WhiteSpace.IncrementDecrementSpacing test.php
  3. See the error message displayed
-----------------------------------------------------------------------------------------
FOUND 2 ERRORS AFFECTING 2 LINES
-----------------------------------------------------------------------------------------
 3 | ERROR | [x] Expected no spaces between the decrement operator and $i; newline found
 7 | ERROR | [x] Expected no spaces between $i and the decrement operator; 0 found
-----------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY
-----------------------------------------------------------------------------------------

Expected behavior

I would expect the message for the post-decrement operator to be "Expected no spaces between $i and the decrement operator; newline found" instead of "Expected no spaces between $i and the decrement operator; 0 found" (newline instead of 0).

Possible solution

I think this problem is caused by using the wrong variable in this line: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/ad5421c0aec2f4cef2148c4a4a5f867a7cae3668/src/Standards/Generic/Sniffs/WhiteSpace/IncrementDecrementSpacingSniff.php#L138

$prevNonEmpty should be used instead of $nextNonEmpty.

I can submit a PR with a patch if it helps.

Versions (please complete the following information)

Operating System Ubuntu 23.04
PHP version 8.3
PHP_CodeSniffer version master
Standard Generic
Install type git clone

Please confirm:

jrfnl commented 7 months ago

Good catch. Probably never reported/caught before as the bug only has effect on the error message, not on whether the error is thrown, nor on the fixer.

If you want to submit a patch, go for it!