-
-
Notifications
You must be signed in to change notification settings - Fork 8
Description
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.TrailingComma
Not covered in PER.
A list of attributes in a block is allowed to have a trailing comma.
This can help with keeping diffs to a minimum when dealing with a multi-line attribute list.
For lack of a PER rule, I'd like to suggest a sniff to enforce the following:
- Forbid a trailing comma when the attribute block is single-line.
- Forbid a trailing comma when the attribute block is multi-line, but only contains the instantiation of a single attribute.
- Enforce a trailing comma when the attribute block is multi-line and lists multiple attributes.
This would not conflict with PER, though it would probably be a good idea to open a discussion about this in the PER repo too.
It could be considered to make the criteria configurable, but that would make the sniff infinitely more complex, so I'd like to suggest starting with a single set of criteria and only making the sniff configurable if there would be user requests to do so.
Notes for the implementation
This sniff could benefit from the upcoming PHPCSUtils AttributeBlock::getAttributes()
method.
Describe the solution you'd like
A new sniff as outlined above.
The sniff should be able to flag and auto-fix the following:
#[AttributeOne] // OK.
#[AttributeOne, AttributeTwo] // OK.
#[AttributeOne(
name: VALUE,
)] // OK.
#[AttributeOne, AttributeTwo,] // Error (should not have trailing comma).
#[
AttributeOne,
AttributeTwo // Error (should have trailing comma).
]
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.