Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Codesniffer custom rule: constant ::class instead of string

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

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

Instead of using:

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

For a couple of reasons we want to add a PHP CodeSniffer rule to catch these strings and add a warning so the string can be refactored to the ::class constant. The first part (catching the string) is easy, but because we are doing static code analysis we can't do (for example) a class_exists or looking up the results of get_declared_classes().

Next option could be analyzing the string itself ([A-Za-z0-9]), but this is not very reliable because a lot of strings will match but are not meant to be a classname.

Another option is to first 'collect' all the classnames (based on T_CLASS token) and analyze all strings after that based on the collected list of classes. Not very easy to implement IMHO because CodeSniffer works on a per-file basis.

Last option i could think about is also quite dirty; because we always use composer in our projects we could take the autoloading files of composer and try to match against the classmaps and namespaces. Also not very reliable and clean.

Anybody with another suggestion we didn't think about?!

like image 349
Arjan Avatar asked Oct 29 '22 21:10

Arjan


1 Answers

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

The best is to use it with EasyCodingStandard like this:

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

Install:

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

Run:

vendor/bin/ecs check src

Fix:

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.

like image 53
Tomas Votruba Avatar answered Nov 15 '22 07:11

Tomas Votruba