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
786 stars 47 forks source link

Terminal comma to indicate discarded items in array destructuring fails Squiz.Arrays.ArrayDeclaration.CommaAfterLast #528

Open joachim-n opened 1 week ago

joachim-n commented 1 week ago

Describe the bug

Array destructuring is a syntax in PHP where items of an array are assigned to single variables, using an array construct on the left of the assignment, e.g.

[$foo, $bar, $baz] = $source_array;

It's a common pattern to include a terminal comma to indicate that we know not all of the array's elements are being assigned.

E.g. in Composer:

[$response, ] = $spec;

                    [$defaultUsername, ] = explode(':', $authParts, 2);

However, this fails the Squiz.Arrays.ArrayDeclaration.CommaAfterLast sniff:

124 | ERROR | [x] Comma not allowed after last value in single-line array
     |       |     declaration (Squiz.Arrays.ArrayDeclaration.CommaAfterLast)

Code sample

<?php

[$alpha, ] = explode('/', 'alpha/beta');

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 test.php
  3. See error message displayed
    3 | ERROR | [x] Comma not allowed after last value in single-line array declaration

Expected behavior

A clear and concise description of what you expected to happen.

Versions (please complete the following information)

Operating System MacOS 10.15
PHP version 8.3
PHP_CodeSniffer version 3.10.1
Standard Squiz
Install type Composer

Additional context

Add any other context about the problem here.

Please confirm

jrfnl commented 1 week ago

@joachim-n Thank you for reporting this. This is due to the sniff incorrectly acting on short lists.

The Squiz.Arrays.ArrayDeclaration sniff is known to be problematic and has been for years.

I've been building up a (highly configurable) NormalizedArrays standard in PHPCSExtra to replace it, but that's not complete yet. Would be lovely if I could find some time to finish that at some point.

Having said that, you could consider excluding the Squiz.Arrays.ArrayDeclaration.CommaAfterLast error code and using the PHPCSExtra NormalizedArrays.Arrays.CommaAfterLast sniff to replace it. That sniff does ignore short lists correctly.

jrfnl commented 1 week ago

Loosely related to #527

joachim-n commented 1 week ago

Thanks for the super quick response!

I've passed on the advice about using a different sniff to the issue in Drupal that brought me here - https://www.drupal.org/project/coder/issues/3456683