Skip to content

[FR] Attributes: sniff to enforce correct indentation for attribute blocks #393

@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 sniff: Universal.Attributes.BlockIndentation

Not explicitly covered in PER.

Proposed rule "Attribute blocks which are on their own line, should be indented the same as the structure they apply to".

Notes for the implementation

This sniff could benefit from the upcoming PHPCSUtils AttributeBlock::appliesTo() method and/or the upcoming PHPCSUtils *::getAttributeOpeners() methods (depending on the chosen entry point for sniffing).

Suggested error codes:

  • Incorrect

Other notes:

  • May also need updating of the PHPCS native ScopeIndent sniff.
    => Needs further investigation.

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.
class Foo {
    #[MyAttribute]
    public const BAR = true;
}

// Error.
class Foo {
#[MyAttribute]
    public const BAR = true;

        #[MyAttribute]
    var $property = [];
}

Also see the examples outlined in the PER documents (rules + migration guide) (even though they haven't made the rule explicit, their code sample do follow it).

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

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions