PHP_CodeSniffer icon indicating copy to clipboard operation
PHP_CodeSniffer copied to clipboard

Squiz.Arrays.ArrayDeclaration.NoComma produces invalid code with heredoc values

Open anbuc opened this issue 3 years ago • 0 comments

Describe the bug This happens when heredoc/nowdoc is used as array values, the array has keys, the comma is directly after the ending nowdoc element in the same line, and the element with the array key is not the last element. phpcbf puts the comma from the nowdoc element into the next line, regardless of what is already in that line

Code sample

<?php

$array = [
    0 => <<<STR
        1
        2
        3
        STR,
    1 => '',
];

To reproduce Steps to reproduce the behavior:

  1. Create a file called test.php with the code sample above...
  2. Run phpcs --standard=squiz --sniffs=Squiz.Arrays.ArrayDeclaration -s test.php
  3. See error message displayed
---------------------------------------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
---------------------------------------------------------------------------------------------------------------
 4 | ERROR | [x] Each line in an array declaration must end in a comma
   |       |     (Squiz.Arrays.ArrayDeclaration.NoComma)
---------------------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
---------------------------------------------------------------------------------------------------------------

When running phpcbf with the same settings, the file looks like this

<?php

$array = [
    0 => <<<STR
        1
        2
        3
        STR
    1 => '',,
];

The error does not happen if

  • The array has no keys (no fix at all)
  • There's an empty line between the elements (the comma will be in that empty line, so at least the syntax is correct
  • The nowdoc is the last element (the comma will be before the ending ];, again at least valid code)

Expected behavior Don't complain because it obviously ends in a comma, and even if, don't produce invalid output

Versions (please complete the following information):

  • OS: Ubuntu 21.04
  • PHP: 7.4.16
  • PHPCS: 3.6.0
  • Standard: squiz

anbuc avatar Jul 26 '21 15:07 anbuc