Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic.NamingConventions.ConstructorName matches methods in anon classes with same name as containing class #2178

Closed
mainframe98 opened this issue Oct 5, 2018 · 1 comment · Fixed by #2182
Milestone

Comments

@mainframe98
Copy link

Whenever a class has a method that uses an anonymous class that itself has a method that matches the name of the containing class, PHP_CodeSniffer reports that the class uses an old style constructor.

<?php
class Nested {
    public function getAnonymousClass() {
        return new class() {
            public function nested() {
                echo 'In method nested!';
            }
        };
    }
}

$nested = (new Nested())->getAnonymousClass();
$nested->nested();

Running with php Nested.php shows:
In method nested!

Running PHP_CodeSniffer, it reports that an old style constructor is used:

FILE: Nested.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
 8 | ERROR | PHP4 style constructors are not allowed; use
   |       | "__construct()" instead
   |       | (Generic.NamingConventions.ConstructorName.OldStyle)
----------------------------------------------------------------------

Had an old style constructor been used, the line In method nested! should have appeared in the output twice, once for the constructor on line 15, and once for the method call on line 16.

Based on the error message, ConstructorNameSniff::processTokenWithinScope is to blame. From what I can see, it uses the name of the containing class because the anonymous class does not have a name.

Used .phpcs.xml file:

<?xml version="1.0"?>
<ruleset>
    <rule ref="Generic.NamingConventions.ConstructorName.OldStyle"/>
    <file>Nested.php</file>
    <arg name="encoding" value="UTF-8"/>
</ruleset>

Used PHPCS 3.3.2.

@jrfnl
Copy link
Contributor

jrfnl commented Oct 6, 2018

This should be fixed by PR #2182.

@gsherwood gsherwood added this to the 3.4.0 milestone Oct 8, 2018
@gsherwood gsherwood changed the title Generic.NamingConventions.ConstructorName.OldStyle matches methods in anonymous classes named the same as the containing class Generic.NamingConventions.ConstructorName matches methods in anon classes with same name as containing class Oct 11, 2018
gsherwood added a commit that referenced this issue Oct 11, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants