phpcodesnifferphpcs

Discouraged Class Usage PHPCS


Let's say I have these classes:

If this exists ->something(new Old_Class()) or Old_Class::staticMethod() or $oldClass->methodCall() I want a code sniff to warn "Old_Class usage found, recommend using New_Class instead".

I found this sniff Generic.PHP.ForbiddenFunctions but it only seems to catch built-in php functions is_array, is_null, etc.

Do I need to write a custom sniff for this?

If so, what token should I added to the register() function to catch on?


Solution

  • I couldn't use a built-in one. I had to write one using T_STRING.

    public function register()
    {
        return [
            T_STRING,
        ];
    }
    
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
    
        if ($tokens[$stackPtr]['content'] === 'Old_Class') {
            $error = 'Old_Class usage found, consider using New_Class instead.';
            $phpcsFile->addWarning($error, $stackPtr);
        }
    }