Skip to content

Autoloading of sniff fails when multiple classes declared in same file #3145

@aik099

Description

@aik099

Describe the bug
When a sniff PHP file contains multiple PHP classes in it (e.g. sniff class itself and a helper class), then \PHP_CodeSniffer\Autoload::loadFile method called in \PHP_CodeSniffer\Ruleset::registerSniffs method returns the last declared class in that file, which might not be a sniff class at all. As a result that class is treated like a sniff class and nothing good happens.

In my case, that class was with mandatory constructor arguments and PHP_CodeSniffer tried to initiate it like a sniff (without constructor arguments) and I've got a Fatal Error.

Code sample

class TypeCommentStructure
{
    public function __construct(File $phpcsFile, $stackPtr)
    {
    }
}

To reproduce
Steps to reproduce the behavior:

  1. add an above-added class at the bottom of any sniff class containing file
  2. run the ruleset, that contains a sniff that was just added
  3. See error message displayed
PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function CodingStandard\Sniffs\Commenting\TypeCommentStructure::__construct(), 0 passed in /mnt/UserData/home/user/.config/composer/vendor/squizlabs/php_codesniffer/src/Ruleset.php on line 1209 and exactly 2 expected in /mnt/UserData/home/user/project/vendor/aik099/coding-standard/CodingStandard/Sniffs/Commenting/TypeCommentSniff.php:608
      Stack trace:
      #0 /mnt/UserData/home/user/.config/composer/vendor/squizlabs/php_codesniffer/src/Ruleset.php(1209): CodingStandard\Sniffs\Commenting\TypeCommentStructure->__construct()
      #1 /mnt/UserData/home/user/.config/composer/vendor/squizlabs/php_codesniffer/src/Ruleset.php(218): PHP_CodeSniffer\Ruleset->populateTokenListeners()
      #2 /mnt/UserData/home/user/.config/composer/vendor/squizlabs/php_codesniffer/src/Runner.php(332): PHP_CodeSniffer\Ruleset->__construct(Object(PHP_CodeSniffer\Config))
      #3 /mnt/UserData/home/user/.config/composer/vendor/squizlabs/php_codesniffer/src/Runne... (182 more bytes) ...
(Run with `--trace` for a full exception trace.)

Expected behavior
A clear and concise description of what you expected to happen.

Versions (please complete the following information):

  • OS: Linux
  • PHP: 7.2
  • PHPCS: 3.5.8
  • Standard: any

Additional context
No issue at PHP_CodeSniffer 3.5.6 and below. The issue started happening after PHP_CodeSniffer 3.5.7 release.

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