1

I'm working on a sniff for PHP_CodeSniffer 3.x. For example, the class declaration class NoInlineFullyQualifiedClassNameUnitTestInc extends \PSR2R\Base\AbstractBase should be split into a uses and class AbstractBase. The sniff detects similar issues for method signatures.

I believe the problem is that I'm generating and inserting multiple use statements at the same line (i.e., same token), but doing so in separate fixer->beginChangeset() ... fixer->endChangeset() sequences. The fixer treats multiple sets of changes to the same token as a conflict, and things get messy (and wrong).

The GitHub issue is here: https://github.com/php-fig-rectified/psr2r-sniffer/issues/9

Has anyone figured out how to do this writing custom sniffs for the latest 3.x CodeSniffer?

Edward Barnard
  • 346
  • 3
  • 17

2 Answers2

1

You can also use SlevomatCodingStandard\Sniffs\Namespaces\ReferenceUsedNamesOnlySniff

It turns this

Before fixing

Into this

After fixing


How to use it?

The best is to use it with EasyCodingStandard like this:

# easy-coding-standard.neon
checkers:
    - SlevomatCodingStandard\Sniffs\Namespaces\ReferenceUsedNamesOnlySniff

Install it:

composer require --dev symplify\easy-coding-standard 

Run it:

vendor/bin/ecs check src

Fix it:

vendor/bin/ecs check src --fix

Enjoy and let me know how it works for you.

If any troubles come up, just create an issue here. I'm happy to improve this tool as much as possible.

Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115
0

The problem is multiple Sniffer (fixer) changesets editing the same token. I was able to get the Sniff to work by collecting a list of USE statements and inserting them at the end of the Sniff's processing.

I identified the end of processing by searching backwards from the last token to find the first token of the list of registered tokens.

Edit: Here is the sniff: https://github.com/php-fig-rectified/psr2r-sniffer/blob/master/PSR2R/Sniffs/Namespaces/NoInlineFullyQualifiedClassNameSniff.php

Edward Barnard
  • 346
  • 3
  • 17