Skip to content

[FR] Named arguments: sniff to enforce spacing around the colon #440

Description

@rodrigoprimo

Setting the scene

PHP 8.0 introduced support for named arguments via the name: $value syntax. At this moment, neither PHPCS itself, nor PHPCSExtra contain a sniff to handle the spacing of named arguments.

The PER Coding Standard from FIG, since PER 2.0, outlines a rule for named-argument spacing to comply with, so using that rule as a starting point would allow for creating a sniff to address it.

Proposed new sniff: Universal.WhiteSpace.NamedArgumentSpacing

To address this rule from PER:

If using named arguments, there MUST NOT be a space between the argument name and colon, and there MUST be a single space between the colon and the argument value.

Notes for the implementation

The sniff has to enforce two things:

  • No space between the argument name and the colon.
  • Exactly one space between the colon and the argument value.

The T_PARAM_NAME token is used for the named argument label and looks like a good entry point for this sniff. Registering T_PARAM_NAME means the sniff does not have to disambiguate the context in which the T_COLON is used.

Suggested error codes:

  • SpacingBefore
  • SpacingAfter

The SpacesFixer from PHPCSUtils should make this fairly straightforward to write, following the same approach as the existing Universal.WhiteSpace.FirstClassCallableSpacing sniff.

The sniff should be configurable and use PER-CS values as default values:

  • public $spacingBefore = 0;
  • public $spacingAfter = 1;

Describe the solution you'd like

A new sniff as outlined above.

The sniff should be able to flag and auto-fix the following:

// OK.
foo(name: $value);

// Error: space before the colon.
foo(name : $value);

// Error: no space after the colon.
foo(name:$value);

// Error: more than one space after the colon.
foo(name:   $value);

// Error: a newline after the colon.
foo(
    name:
        $value,
);

Also see the examples outlined in the PER documents (rules + migration guide).

Additional context (optional)

This ticket is the result of a detailed analysis of the rules as outlined in PER-CS 2.0, as well as a critical look at what's still missing rule-wise.

  • I intend to create a pull request to implement this feature.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions