0

Let's say I have these classes:

  • Old_Class
  • New_Class

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?

Jrow
  • 1,026
  • 2
  • 12
  • 31

2 Answers2

0

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);
    }
}
B25Dec
  • 2,301
  • 5
  • 31
  • 54
Jrow
  • 1,026
  • 2
  • 12
  • 31
0

I know this is a fairly old question, but there are two possible solutions I'm aware of:

  1. The Slevomat coding standard for Codesniffer includes a sniff to report usage of any of an array of forbidden classes
  2. Static analysis tools are another approach for this. If you mark a class with the @deprecated annotation, I know from personal experience that Psalm will flag it with the DeprecatedClass issue, and if you can't fix them all at once, you can add them to the baseline, which will suppress the issue, but keep track of it, so you can still use Psalm in continuous integration and not break on existing issues. I believe PHPStan has similar functionality.
Matthew Daly
  • 9,212
  • 2
  • 42
  • 83
  • There's now another possible solution for this - the [Pest Architecture plugin](https://pestphp.com/docs/arch-testing) allows you to write a test which fails if a specific class is used withing a given namespace. – Matthew Daly Aug 12 '23 at 17:10