WordPress-Coding-Standards icon indicating copy to clipboard operation
WordPress-Coding-Standards copied to clipboard

Add rule for list() associative array destructure for multiline formatting

Open abdul-alhasany opened this issue 4 years ago • 0 comments

Is your feature request related to a problem?

PHP 7.1.0 introduces associative array destructuring using list() construct. It would be a nice addition to format the associative destructure inside list() with the same rule as arrays. Currently, list() is not broken into multi line regardless of the line max limit.

Describe the solution you'd like

list() could be formatted like so:

list( 
    'show' => $show,
    'position' => $position,
    'align' => $align
) = $array;
  • Each pair on a single line
  • Opening brackets same line as list construct
  • Closing bracket, equal operator and variable on the same line
  • Possibly a trailing comma for the last pair
  • This rule should not apply for a single line destructure (if it is less than line limit)

Additional context

list() can be written using shorthand syntax:

[
  'show' => $show,
  'position' => $position,
  'align' => $align
] = $array;

But this is not accepted using PHPCS rule 'Generic.Arrays.DisallowShortArraySyntax.Found' and they square brackets are converted to array() which is not a shorthand list() syntax. This can be "fixed" by letting PHPCS format the code with array() then convert it to square brackets and add this to ignore the rule:

//phpcs:ignore Generic.Arrays.DisallowShortArraySyntax.Found
[
  'show' => $show,
  'position' => $position,
  'align' => $align
] = $array;

But this not ideal if there are many instances of it.

list() also accept multidimensional destructuring.

list(
    'show' => $show,
    'align' => $align
    'position' => [
        'top' => $top,
        'bottom' => $bottom,
    ]
) = $array;

PHP list()

abdul-alhasany avatar Oct 17 '21 02:10 abdul-alhasany