PHP-CS-Fixer: Reference assignment operator =& gets broken up

Bug report

Description

The binary_operator_spaces fixer using at_least_single_space (part of PSR12 ruleset since recently) will break up the reference assignment operator =& by inserting a space between the two parts:

<?php
$a =& $b;
// becomes
$a = & $b;

I think this should either be left as $a =& $b (preferred) or become $a = &$b (misleading), but the chosen form of $a = & $b is not a style I have ever seen.

Runtime version

PHP CS Fixer 3.26.1 Crank Cake by Fabien Potencier and Dariusz Ruminski. PHP runtime: 8.1.2-1ubuntu2.14

Command

php-cs-fixer fix test.php --rules=@PSR12

About this issue

  • Original URL
  • State: closed
  • Created 9 months ago
  • Comments: 16 (8 by maintainers)

Commits related to this issue

Most upvoted comments

That might actually be better, yeah! And also allow for only handling e.g. assignments, if only that is the desired case.

I might give it a try, but since it’s my first time working with PHP-CS-Fixer core, the PR will probably need some work and comments! 😉

Thank you for the explanation 🙂. We probably need to make sure that it is just left as-is, regardless if it’s =& $foo or = &$foo and then probably introduce assign_by_reference fixer to standardise it?

Yeah, I think that would be the ideal thing to do.

It’s a bit of a tricky question. & is not a standalone operator and cannot appear in arbitrary expressions – $a + &$b is not a valid expression. It is only allowed in a few specific places, one of those being the combination of = and &. In that sense, =& should be seen as a single operator, rather than the combination of a binary and (non-existent) unary operator. At the same time, PHP does not have a dedicated token for =& and instead handles this as a combination of the = and & tokens, which is what allows placing whitespace between = and & in the first place (e.g. one couldn’t write & =, but one can write = &). In that sense, these are separate operators.

I guess the expected formatting of reference assignment is something that PER may want to clarify. I think there is a problem on the PHP-CS-Fixer side either way though, as it should produce one of $a =& $b or $a = &$b, but not $a = & $b.