Search code examples
phpcodesniffer

How to create multiple USE statements in sniff


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?


Solution

  • 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