PHP Codesniffer rule: constant :: class instead of string

In the codebase of one of my clients, I see many references to the qualified class name as a string;

[ 'foobar' => 'My\Namespace\Class' ] 

Instead of using:

 [ 'foobar' => My\Namespace\Class::class ] 

For two reasons, we want to add the PHP CodeSniffer rule to catch these lines and add a warning so that the line can be reorganized into the :: class constant. The first part (catching the string) is simple, but since we are doing static code analysis, we cannot do (for example) the exists_class or look for the results of get_declared_classes ().

The next parameter can be analyzed by the string itself ([A-Za-z0-9]), but this is not very reliable, because many lines will correspond, but are not intended for the class name.

Another option is to first โ€œcollectโ€ all class names (based on the T_CLASS token) and analyze all the lines after that based on the assembled list of classes. IMHO is not very easy to implement, because CodeSniffer works on a per-file basis.

The last option I could think of is also quite dirty; because we always use the composer in our projects, we can take the autoload files of the composer and try to match them with classes and namespaces. Also not very reliable and clean.

Anyone with a different sentence that we did not think about ?!

+5
source share
1 answer

Good news! I created this latch - you can find it here .

It is best to use it with EasyCodingStandard as follows:

 # ecs.yml services: Symplify\CodingStandard\Fixer\Php\ClassStringToClassConstantFixer: ~ 

Installation:

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

To run:

 vendor/bin/ecs check src 

Fix:

 vendor/bin/ecs check src --fix 

Enjoy and let me know how this works for you.

If you encounter any problems, just create a problem here . I am happy to improve this tool as much as possible.

+2
source

All Articles