Terminal comma to indicate discarded items in array destructuring fails sniffs

Created on 24 June 2024, 5 days ago

Problem/Motivation

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;

(see https://www.php.net/manual/en/language.types.array.php)

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 Drupal\Core\DependencyInjection\YamlFileLoader

            [$provider, ] = explode('.', $basename, 2);

This is used in code outside of Drupal too, e.g. in Composer:

                        [$response, ] = $spec;

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

However, Coder fails this with two sniffs:

124 | ERROR | [x] Comma not allowed after last value in single-line array
     |       |     declaration (Squiz.Arrays.ArrayDeclaration.CommaAfterLast)
 124 | ERROR | [x] There should be no white space before a closing "]"
     |       |     (Drupal.WhiteSpace.CloseBracketSpacing.ClosingWhitespace)

I've created an upstream issue for Squiz.Arrays.ArrayDeclaration.NoCommaAfterLast: https://github.com/PHPCSStandards/PHP_CodeSniffer/issues/528

Steps to reproduce

Proposed resolution

Remaining tasks

User interface changes

API changes

Data model changes

πŸ› Bug report
Status

Active

Version

8.3

Component

Coder Sniffer

Created by

πŸ‡¬πŸ‡§United Kingdom joachim

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @joachim
  • πŸ‡¬πŸ‡§United Kingdom joachim
  • πŸ‡¬πŸ‡§United Kingdom joachim

    I got a very quick response to my upstream issue:

    > 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.

Production build 0.69.0 2024