Skip to content

[FR] Attributes: sniffs to standardize the use of parentheses on attribute instantiation #387

@jrfnl

Description

@jrfnl

Setting the scene

PHP 8.0 introduced support for attributes via the #[...] syntax. At this moment, neither PHPCS itself, nor PHPCSExtra contain any sniffs to handle the formatting of attributes.

The PER Coding Standard from FIG, since PER 2.0, outlines a set of rules for attribute formatting to comply with, so using those rules as a starting point would allow for creating an initial set of sniffs to address attribute formatting.

Proposed new sniffs: Universal.Attributes.RequireParentheses and Universal.Attributes.DisallowParentheses (only when no parameters obviously)

To address these rules from PER:

If an attribute has no arguments, the () MUST be omitted.

I deliberately propose two separate sniffs to give users a choice of what they want to enforce as not everyone will want to use the PER rules.

Notes for the implementation

This sniff could benefit from the upcoming PHPCSUtils AttributeBlock::getAttributes() method.

There is a similar set of sniffs for anon class parentheses already available in PHPCSExtra.

Describe the solution you'd like

A new sniff as outlined above.

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

// Universal.Attributes.RequireParentheses
#[MyAttribute()] // OK.
#[MyAttribute] // Error.

// Universal.Attributes.DisallowParentheses
#[MyAttribute] // OK.
#[MyAttribute(PARAM)] // OK.
#[MyAttribute()] // Error.

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

Additional context (optional)

This ticket is part of a series of tickets related to PHP attributes and is the result of a detailed analysis of the rules as outlined in PER 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