Search code examples
phpstatic-analysisphpstan

How can I have phpstan find my custom extension class?


To implement checks for some magic _get() functions, I'm trying to implement a "class reflection extension". The manual mentions how to write the extension files themselves, and to install them by adding a service part to the neon file.

I've written an extension, and added it like so:

services:
    -
        class: TestClass
        tags:
            - phpstan.broker.methodsClassReflectionExtension

This results in the following error:

Service '0226': Class TestClass not found.

Things I've tried:

  • using the standalone phar
  • using the composer install of phpstan
  • using a specific namespace (PHPStan) for the extension (in the file and in the neon)
  • using a "random" namespace (in the file and in the neon)
  • Adding the file to a directory I know is being scanned for analysis
  • Adding the directory with the extension to the "scanDirectories" parameter
  • Adding the file to the "scanFiles" parameter
  • Adding the directory with the extension to the "paths" parameter
  • Adding a (deprecated) autoload directive and adding the file there.

Several of these 'adding' tries actually warn if the file is not found: if, for instance, I make a deliberate typo in one of these, lets say the autoload one, it will warn me of a missing file. But only if I don't have the service defined.

If I have the service defined and the deliberate typo in there, it returns above class-not-found (and not the typo), so I feel it's checking the extension before any of the parameters?

There seems to be a need for adding my file to a different autoloading mechanism. The question is, which and how?

I'm using

  • phpstan 0.12.40
  • php 7.2.33

Solution

  • The extension class needs to be loaded in runtime. You can achieve that in two ways:

    1. Make the class available for the Composer autoloader. It's usually sufficient to configure autoload-dev section of your composer.json.

    2. Create a file called something like phpstan-autoload.php in which you require_once the file with the extension class. And pass the path to the phpstan-autoload.php file as --autoload-file|-a option on the command line when running PHPStan.