djoos / Symfony-coding-standard

Development repository for the Symfony coding standard
MIT License
402 stars 102 forks source link

Anonymous classes break several sniffs. #153

Closed Ma27 closed 5 years ago

Ma27 commented 5 years ago

It seems as the usage of anonymous classes breaks the Symfony.Objects.ObjectInstantiation.Invalid and Symfony.Classes.PropertyDeclaration.Invalid sniff. The problem can be demonstrated with a class like this:

<?php

namespace App;

/**
 * DemoFactory.
 */
class DemoFactory
{
    /**
     * Creates a demo instance.
     *
     * @return DemoInterface
     */
    public function createDemo(): DemoInterface
    {
        return new class() implements DemoInterface
        {
            /**
             * @var mixed
             */
            private $property;

            /**
             * Get property.
             *
             * @return mixed
             */
            public function getProperty()
            {
                return $this->property;
            }
        };
    }
}

Running phpcs with this ruleset causes the following errors:

λ ma27 [~/Projects/phpcs-sf-bug] → ./vendor/bin/phpcs class.php --standard=Symfony -n    

FILE: /home/ma27/Projects/phpcs-sf-bug/class.php
----------------------------------------------------------------------
FOUND 2 ERRORS AFFECTING 2 LINES
----------------------------------------------------------------------
 17 | ERROR | Use parentheses when instantiating classes
 22 | ERROR | Declare class properties before methods
----------------------------------------------------------------------

Time: 72ms; Memory: 6MB

The latest code standard document doesn't mention anonymous classes at all, so it's also possible that its usage isn't intended. In that case it should be sufficient to add an error for the entire new class expression stating that it shouldn't be used.

lheckemann commented 5 years ago

+1. This also applies to Symfony.Functions.ScopeOrder.Invalid when the method in which an anonymous class is used is not public.