Problem/Motivation
When authoring a class using PHP 8, it is now possible to attach attributes to classes. When attributes are used on classes, though, PHPCS/Coder complain that the docblock for the class is missing unless the docblock appears between the attribute and the class name.
This does not affect attributes on methods, for which it would appear that a change was made back in February 2023.
Steps to reproduce
- Within a Drupal module, create a source file called
src/TestAttributes.php.
- Paste the following code into the new file:
<?php
namespace Drupal\MY_MODULE;
/**
* My class comment.
*/
#[\Attribute]
class AllGood {
}
- Run PHPCS with the
Drupal coding style on the module.
- Move the attribute above the docblock, as follows:
<?php
namespace Drupal\MY_MODULE;
#[\Attribute]
/**
* My class comment.
*/
class AllGood {
}
- Re-run PHPCS.
When the attribute is right above the class, this is the error:
FOUND 1 ERROR AFFECTING 1 LINE
--------------------------------------------------------------------------------
9 | ERROR | [x] Missing class doc comment (Drupal.Commenting.ClassComment.Missing)
--------------------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
--------------------------------------------------------------------------------
The error does not appear if the attribute is above the comment, but that doesn't look right.
Proposed resolution
Tweak the sniff so it allows annotations above classes the same way it allows them on methods; below is what's allowed for methods:
/**
* Test PHP attributes.
*/
class TestPhpAttributes {
/**
* Tests method with PHP attribute and docblock.
*/
#[\ReturnTypeWillChange]
public function attributes(): void {
}
}
Remaining tasks
User interface changes
API changes
Data model changes
Comments
Comment #2
guypaddock commentedAs a workaround, this appears to work:
In the code above,
OtherClasswill get the warning (as intended) butAllGoodwill not.Comment #3
guypaddock commentedComment #4
guypaddock commentedComment #5
guypaddock commentedComment #6
klausiThanks for reporting!
I started a fix at https://github.com/pfrenssen/coder/pull/179 , but the fixer does not work correctly yet.
Comment #8
klausiImproved the fixer and merged it!
Comment #9
claudiu.cristeaThis is only fixing the case when there's one attribute. But a method might expose multiple attributes. The following will fail with: Missing class doc comment (Drupal.Commenting.ClassComment.Missing)
Comment #10
klausiThanks for reporting, I'll put that in as test case and will check.
Comment #12
klausiAdded a test case for class comments, there it works as expected.
It looks like you are talking about method attributes, which are not checked in the class comment sniff. Will open a new issue to check for that.
Comment #13
klausiCreated #3345952: Wrong error on function doc comments when 2 attributes are used.