Skip to content

PSR12.Classes.ClassInstantiation.MissingParentheses false positive using attributes on anonymous class #3456

@vaceletm

Description

@vaceletm

Describe the bug

When attributes are set on anonymous classes, phpcs inappropriately flag PSR12.Classes.ClassInstantiation.MissingParentheses violation

Code sample

<?php

$class1 = new class {
    #[SomeAttribute('summary')]
    public const SOME_STUFF = 'foo';
};

$class2 = new #[SomeAttribute('summary')] class {
    public const SOME_STUFF = 'foo';
};

Custom ruleset

PSR12

To reproduce
Steps to reproduce the behavior:

  1. Create a file called test.php with the code sample above...
  2. Run ./vendor/bin/phpcs --standard=PSR12 test.php ...
  3. See error message displayed
-------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
-------------------------------------------------------------------------
 8 | ERROR | [x] Parentheses must be used when instantiating a new class
-------------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
-------------------------------------------------------------------------

Expected behavior

  1. Should'nt report an error at Line 8
  2. phpcbf shouldn't attempt to fix by producing invalid code

Versions (please complete the following information):

  • OS: Linux Fedora 34
  • PHP: 8.0
  • PHPCS: 3.6.1
  • Standard: PSR12

Additional context

phpcbf will produce invalid code:

./src/vendor/bin/phpcbf --standard=PSR12 test.php 

PHPCBF RESULT SUMMARY
----------------------------------------------------------------------
FILE                                                  FIXED  REMAINING
----------------------------------------------------------------------
/home/mvacelet/workspace/tuleap/test.php             1      0
----------------------------------------------------------------------
A TOTAL OF 1 ERROR WERE FIXED IN 1 FILE
----------------------------------------------------------------------

and resulting file:

<?php

$class1 = new class {
    #[SomeAttribute('summary')]
    public const SOME_STUFF = 'foo';
};

$class2 = new() #[SomeAttribute('summary')] class {
    public const SOME_STUFF = 'foo';
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions