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.dist.neon file to the root of your project.

yaml
parameters:
    paths:
        - app
    level: 8

TIP

New projects should start at level 8. Legacy projects may start at level 6 and work up incrementally as the codebase is brought up to standard.

TIP

Use phpstan.dist.neon for the shared, tracked configuration. PHPStan does not automatically merge config files, so for local-only overrides (e.g. an IDE editor link), create a gitignored phpstan.neon file that explicitly includes it:

yaml
includes:
    - phpstan.dist.neon

parameters:
    editorUrl: 'phpstorm://open?file=%%file%%&line=%%line%%'

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 larastan/larastan --dev

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

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

Recommended configuration is to add the following as parameters in your phpstan.dist.neon file. checkOctaneCompatibility is included by default, even if the project isn't currently using Laravel Octane, since it catches state-leakage bugs worth avoiding regardless.

yaml
checkModelProperties: true
checkMissingIterableValueType: false
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.dist.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