Search code examples
cakephpphpstan

PHPStan reporting "extends unknown class" for a core CakePHP feature


I have a web application which is running on CakePHP 4.4.4

I have recently started using PHPStan with the codebase running at level 1. This level is specified in our configuration file, phpstan.neon

After generating a baseline with

vendor/bin/phpstan analyse --configuration phpstan.neon src/ tests/ --generate-baseline 

this added approx 80 errors to phpstan-baseline.neon. There was a message saying some errors couldn't be baselined and the advice was to re-run PHPStan.

On running vendor/bin/phpstan analyse src/ --memory-limit=1G it reported 6 errors about a CakePHP class which is being used in a few different files inside src/Command/. One such example is:

Class App\Command\AlertsCommand extends unknown class Cake\Console\Command.

If I open the file it's referring to, src/Command/AlertsCommand.php, we have this:

<?php
namespace App\Command;

use Cake\Console\Command;

class AlertsCommand extends Command
{
    public function initialize(): void
    {
        parent::initialize();
        // ...
    }
 
    // Other functions for this command defined here onwards

}

VSCode red-underlines "Command" (as in extends Command) and a tooltip says

Undefined type 'Cake\Console\Command'

When referring to the CakePHP 4 docs here https://book.cakephp.org/4/en/console-commands/commands.html I noticed it has use Cake\Command\Command; as opposed to use Cake\Console\Command;. I updated this and re-ran PHPStan.

The number of errors increased from 6 to 7 with a message specifically about this change which said:

Ignored error pattern #^App\Command\AlertsCommand::initialize() calls parent::initialize() but App\Command\AlertsCommand does not extend any class.$# in path src/Command/AlertsCommand.php was not matched in reported errors.

This doesn't make any sense. It says - quote - "AlertsCommand does not extend any class" but clearly it does:

class AlertsCommand **extends Command** 

The application itself works so none of the original code - before making the use modification - is stopping anything from working.


Solution

  • PHPStan tells you:

    Ignored error pattern … was not matched in reported errors.

    This means you’re ignoring something that’s no longer happening. You can just remove this ignored error from config/baseline.

    You can also set reportUnmatchedIgnoredErrors: false and this is not going to be reported. See the documentation: https://phpstan.org/user-guide/ignoring-errors#reporting-unused-ignores