`Drupal.Commenting.ClassComment.Missing` Appears when Using PHP 8 Class Attributes

Created on 18 November 2022, over 1 year ago
Updated 4 March 2023, over 1 year ago

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.

<!--break-->

This does not affect attributes on methods, for which it would appear that a change was made back in February 2023.

Steps to reproduce

  1. Within a Drupal module, create a source file called src/TestAttributes.php.
  2. Paste the following code into the new file:
    <?php
    
    namespace Drupal\MY_MODULE;
    
    /**
     * My class comment.
     */
    #[\Attribute]
    class AllGood {
    }
    
  3. Run PHPCS with the Drupal coding style on the module.
  4. Move the attribute above the docblock, as follows:
    <?php
    
    namespace Drupal\MY_MODULE;
    
    #[\Attribute]
    /**
     * My class comment.
     */
    class AllGood {
    }
    
  5. 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

πŸ› Bug report
Status

Fixed

Version

8.3

Component

Coder Sniffer

Created by

πŸ‡ΊπŸ‡ΈUnited States GuyPaddock

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024