Skip to content

PHPStan

PHPStan is a static analysis tool for PHP. It will analyse and report on any coding issues it can interpret from code typehinting.

Configuration

Copy the following as a phpstan.neon file to the root of your project.

yaml
parameters:
    paths:
        - app
    level: 6

To run the linter, run phpstan from the command line.

bash
./vendor/bin/phpstan analyse

It is recommended to configure an analyse Composer script by adding the following to the scripts section in composer.json:

json
"analyse": "@php vendor/bin/phpstan analyse"

Then PHPStan can be triggered with:

bash
composer analyse

Laravel

For Laravel, install Larastan.

bash
  composer require nunomaduro/larastan --dev

Ensure you have the PHPStan extension installer installed or manually include it in your phpstan.neon file.

yaml
includes:
    - ./vendor/nunomaduro/larastan/extension.neon

Recommended configurations is to add the following as parameters in your phpstan.neon file.

yaml
checkModelProperties: true
checkMissingIterableValueType: false

If there is a possibility of using Laravel Octane, it is recommended to add the following to your parameters in your phpstan.neon file.

yaml
checkOctaneCompatibility: true

Baseline

Ideally, PHPStan should pass without any errors. However in some situations (particularly on older projects) it may be necessary to generate a baseline to 'ignore' errors currently raised.

A baseline file can be created or updated as follows:

bash
./vendor/bin/phpstan analyse --generate-baseline

You can then add the phpstan-baseline.neon file to your phpstan.neon file in the includes section.

yaml
includes:
    - ./phpstan-baseline.neon

It is recommended to configure a baseline Composer script by adding the following to the scripts section of composer.json:

json
"baseline": "@php vendor/bin/phpstan analyse --generate-baseline"

Then the baseline can be updated with:

bash
composer baseline

Extensions

When using extensions, it is recommended to install the PHPStan Extension Installer, which will automatically include any PHPStan extenstions you install via composer, rather than having to manually register them.

bash
  composer require phpstan/extension-installer --dev

IDE Support

Related VSCode Extensions

PHPStorm config