squizlabs / PHP_CodeSniffer

PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.
BSD 3-Clause "New" or "Revised" License
10.67k stars 1.48k forks source link

Enforcing spacing in method chaining #3331

Open tpalts opened 3 years ago

tpalts commented 3 years ago

I'm looking for a rule that enforces newline and spacing in method chaining. When chaining is used and there is a line break anywhere in the chain:

Question: What combination of rules could I use to achieve this, if any?

Examples:

Allow:

$x = Model::query()->where('x', 1)->where('y', 2)->get();
$x = Model::query()
    ->where('x', 1)
    ->where('y', 2)
    ->get();

Don't allow:

$x = Model::query()->where('x', 1)
->where('y', 2)->get();

$x = Model::query()
->where('x', 1)
->where('y', 2)
->get();

$x = Model::query()->
    where('x', 1)->
    where('y', 2)->
    get();

Thanks!

jrfnl commented 3 years ago

While it doesn't enforce all the rules you want, the PEAR.WhiteSpace.ObjectOperatorIndent sniff would probably be a good start. Also see the custom properties you can set for it: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties#pearwhitespaceobjectoperatorindent

gsherwood commented 3 years ago

You don't mention if whitespace is allowed around object operators or not, but your code sample shows no spaces so you may want to look at Squiz.WhiteSpace.ObjectOperatorSpacing as well, but set the ignoreNewlines property to TRUE: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Customisable-Sniff-Properties#squizwhitespaceobjectoperatorspacing

Have these suggestions given you enough rules to enforce what you want?