Destructuring syntax (list() and [])
I want to report a case that does not seem to be explicitly covered by PSR-12.
It concerns variable destructuring using the list() and [] syntaxes.
I have this code:
[$val1,$val2] = explode(',', $string);
list($val1,$val2) = explode(',', $string);
And I do not get any error when running the command:
phpcs --standard=PSR12 my-file.php
In my opinion, there should be a space required after the comma following $val1, as in function calls or arrays.
Correction:
[$val1, $val2] = explode(',', $string);
list($val1, $val2) = explode(',', $string);
I'm pretty sure a space is required after any comma. Sounds like something you should take up with php-cs.
PHPCS does exactly what is expected: follow PSR12. PSR12 has no rules about array or list formatting, so PHPCS doesn't enforce any.
And even PER in the current master has no rules about list formatting and has no explicit rule about spacing after a comma for arrays (other than single-line, multi-line).
Surely, it would make sense to have spaces, since 4.7 says:
In the argument list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.
Arguably, these are not function calls, it's arrays and language constructs, so we may need an amendment to explicitly say that the same rule applies there too.
While we don't have specific cases for destructuring, it stands to reason that language constructs like list(...) = would follow the function call rules and [...] = would follow the array declaration rules.
Easy enough to add clarification in a future version but to me there isn't really much ambiguity here and we all know exactly the syntax that would be codified.
Since we're about to tag 3.0, if we want to clarify this further, it sounds like a reasonable 3.1 target.
Happy to see this addressed/made explicit in PER 3.1.
but to me there isn't really much ambiguity here and we all know exactly the syntax that would be codified.
Agreed, but tools like PHPCS also need to be aware of it.
Similarly, this code doesn't raise any PHPCS error:
$array = ['val1','val2','val3'];