Skip to content

PHPStan Static Code Analysis

samuelgfeller edited this page Mar 30, 2024 · 1 revision

Introduction

PHPStan is a static code analysis tool that helps find bugs in the code without running it.

Among other things, PHPStan looks for:

  • Type safety: Ensuring that the methods and functions are called with the correct number of parameters and the correct types.
  • Unused code: Detecting unused variables, unused methods, unused properties, etc.
  • Non-existent classes, methods, properties, or functions: Checking if the classes, methods, properties, or functions that are being called actually exist.
  • Incorrect documentation: Verifying that PHPDoc comments match the actual types of the parameters and return values

Installation

PHPStan can be installed as a development dependency using Composer:

composer require --dev phpstan/phpstan

Configuration

The configuration of PHPStan is done in the phpstan.neon file in the root directory of the project. This file contains the paths to the directories that should be analyzed, special rules and the level of strictness that should be applied.

File .phpstan.neon

parameters:
    level: 8
    checkMissingIterableValueType: false
    paths:
        - src
        - tests

Please refer to the PHPStan documentation to learn how to ignore errors and suppress specific warnings.

Composer command

To run PHPStan with a short command, add the following command to the scripts section of the composer.json file:

"scripts": {
  "stan": "phpstan analyse -c phpstan.neon --no-progress --ansi",
}

Usage

To run PHPStan, execute the following command in the terminal:

composer stan
Clone this wiki locally