PHPCSExtra icon indicating copy to clipboard operation
PHPCSExtra copied to clipboard

[FR] Attributes: sniffs to standardize whether attributes should be FQN or not

Open jrfnl opened this issue 3 months ago • 0 comments

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.EnforceFullyQualified / Universal.Attributes.EnforceUnqualified

Not covered in PER.

Low priority, but I can imagine there may be people who want to enforce that attributes always use fully qualified names. Or the opposite: only allow unqualified names in combination with import use statements.

Notes for the implementation

This sniff could benefit from the upcoming PHPCSUtils AttributeBlock::getAttributes() method, as well as from the existing PHPCSUtils UseStatement methods (and upcoming tracking).

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.EnforceFullyQualified
#[\Fully\Qualified\AttributeName] // OK.

use Fully\Qualified\AttributeName;
#[AttributeName] // Error.


// Universal.Attributes.EnforceUnqualified
use Fully\Qualified\AttributeName;
#[AttributeName] // OK.

#[\Fully\Qualified\AttributeName] // Error.

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.

jrfnl avatar Sep 23 '25 01:09 jrfnl