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 ?!
Arjan source share