PHP Advent

#[Tooling]

PHPStan on Legacy Code: Baselines, Levels, and Green CI

· 14 min read

An illuminated drafting desk holds layered software diagrams beside brass calipers and a green status display.

To add PHPStan to an existing PHP codebase while continuing to ship features, start at rule level 0 or 1 and record existing issues in a baseline file. PHPStan ignores the errors in that file, so your continuous integration pipeline can pass today. Incoming pull requests still fail when they introduce new typing errors or undefined method calls covered by your chosen level.

The first analyzer run on an older PHP application can be discouraging. Years of framework changes, mixed scalar types, dynamic properties, and optional parameters can produce thousands of warnings without configuration. Fixing every warning before enabling the CI check can mean months of blocked tickets. A tracked baseline lets the team keep working on features while fixing older defects as time allows.

Why Legacy Applications Need Static Analysis

Static analysis inspects PHP code without running it. Unit tests execute particular branches with fixed inputs. PHPStan uses code structure and inferred types to flag problems in paths the tests may not cover.

In a legacy application, dynamic typing can hide bugs until an unusual input or failure exposes them. Common issues include passing null to functions expecting strings, calling methods on variables that evaluate to false during database outages, and referencing undefined array keys. While profiling tools such as those discussed in our guide to PHP profiling show where execution slows down, static analysis finds correctness problems before the code reaches staging or production.

Tools like Psalm offer another option for static type checking. PHPStan supports gradual adoption through rule levels, configuration, and baseline generation. Older engineering guides such as Mark Story's legacy jungle make a similar case for automated checks when bringing older applications under control.

Step 1: Installing PHPStan with Composer

Add PHPStan to your project as a development dependency using Composer. Keeping it in require-dev separates development tools from production vendor archives.

composer require --dev phpstan/phpstan

For applications tied to older PHP runtimes, PHPStan provides isolated distribution archives and container images. Running it through Composer in your project environment gives it direct access to the project autoloaders and the types supplied by installed dependencies.

Verify the installation by running the command-line entry point:

vendor/bin/phpstan --version

Detailed installation options, extension installers, and phar distributions are documented in the PHPStan getting started guide.

Step 2: Understanding PHPStan Rule Levels

PHPStan has 11 rule levels, numbered 0 to 10. Each level includes the checks from every lower level and adds stricter ones. The checks at each level are described in the PHPStan rule levels documentation.

Here is what each level checks:

  • Level 0: Basic sanity checks. Validates unknown classes, unknown functions, unknown methods called on $this, incorrect numbers of arguments passed to functions, and completely undefined variables.
  • Level 1: Scope safety. Checks for possibly undefined variables and flags unknown magic methods or properties on classes lacking appropriate PHPDoc annotations.
  • Level 2: Comprehensive method checking. Checks unknown methods across all expressions and objects, not merely $this, and begins validating PHPDoc annotations for syntax errors.
  • Level 3: Return and property types. Inspects return types declared on functions and checks the types of values assigned to class properties.
  • Level 4: Dead code analysis. Flags basic dead code, including impossible instanceof comparisons, unreachable statements following return or throw statements, and always-false else branches.
  • Level 5: Argument type checking. Validates that the types of arguments passed into methods and functions match declared parameter types.
  • Level 6: Typehint completeness. Reports missing type information, including value types for iterable parameters and returns.
  • Level 7: Union type correctness. Flags calls where a method exists on only some types in a union type, preventing partially broken multi-type assumptions.
  • Level 8: Nullable safety. Prevents calling methods or reading properties on expressions that can resolve to null, requiring explicit null checks or assertions.
  • Level 9: Explicit mixed operations. Restricts operations on variables explicitly typed as mixed, allowing them only to be passed to other parameters typed as mixed.
  • Level 10: Implicit mixed operations. Extends level 9 by enforcing strict handling on untyped variables and implicit mixed expressions throughout the codebase.
Five ascending glass steps crossed by two colored light beams illustrate progressively stricter rule levels.

Choosing the Right Starting Level for Legacy Code

Starting at Level 5 or higher is tempting, but a codebase with several years of history may not be ready for it. Strict argument checks or null safety checks on code without annotations can produce tens of thousands of errors. That is a lot for a team to review before it has learned how to use the tool.

Begin at Level 0 or Level 1:

Level 0 catches typos in class names, calls to methods that do not exist, and variables that were never initialized. Each can cause a runtime failure.

Level 1 adds checks for variables that might be undefined under certain conditional branches, such as a variable assigned inside an if block but consumed outside it without an else fallback.

Step 3: Configuring phpstan.neon

PHPStan uses the NEON format for its project configuration file, typically named phpstan.neon or phpstan.neon.dist in the repository root. NEON is a human-readable configuration language similar to YAML, designed specifically for PHP tooling.

The initial configuration sets the rule level and source directories to inspect. It also specifies a temporary cache directory and can load legacy bootstrap files. The full list of settings is in the PHPStan configuration reference.

Create a phpstan.neon file in your project root:

parameters:
    level: 0
    paths:
        - src
        - app
    excludePaths:
        analyse:
            - src/Legacy/Generated
    tmpDir: var/cache/phpstan

Replace src and app with directories that exist in your application. Exclude generated code only when it is outside your control; leave your own tests in scope if you want PHPStan to check them too. Add var/cache/phpstan/ to .gitignore so the result cache does not enter version control.

Handling Legacy Autoloading and Custom Constants

Many older PHP applications do not follow PSR-4 autoloading throughout. They may use procedural bootstrap scripts to define global constants, initialize custom class loaders, or register global helper functions.

If PHPStan reports that classes or constants cannot be found despite existing in your repository, configure bootstrapFiles or scanDirectories:

parameters:
    level: 0
    paths:
        - src
    bootstrapFiles:
        - config/constants.php
        - legacy/custom_autoloader.php
    scanDirectories:
        - legacy/includes

The bootstrapFiles directive runs the specified PHP scripts before analysis starts. This makes global constants and legacy class aliases available in memory. The scanDirectories directive tells PHPStan to parse class and interface definitions in non-PSR-4 folders without directly executing them.

Step 4: Generating and Locking the Baseline

Once phpstan.neon contains your starting level and source paths, run the analysis:

vendor/bin/phpstan analyse

On a large legacy application, expect hundreds or thousands of errors. You can export the current error list to a baseline instead of fixing everything before proceeding or scattering ignore comments through the source.

Generate the baseline using the --generate-baseline command-line option:

vendor/bin/phpstan analyse --generate-baseline

The command analyzes the codebase and writes the reported errors to phpstan-baseline.neon. The baseline groups errors by relative file path. Each entry records the exact error message pattern and the number of times it occurs:

parameters:
    ignoreErrors:
        -
            message: '#^Call to an undefined method App\\Model\\User::getBillingStatus\(\)\.$#'
            count: 1
            path: src/Controllers/BillingController.php
        -
            message: '#^Variable \$taxRate might be undefined\.$#'
            count: 2
            path: src/Services/InvoiceService.php

To activate the baseline, open phpstan.neon and include phpstan-baseline.neon at the top of the file:

includes:
    - phpstan-baseline.neon

parameters:
    level: 0
    paths:
        - src
        - app
    tmpDir: var/cache/phpstan

Run PHPStan again:

vendor/bin/phpstan analyse

If the configuration and baseline cover the current errors, PHPStan filters out those errors and exits with code 0:

 [OK] No errors

Commit the baseline to keep a record of the existing errors in version control. The build can now pass on day one, while new undefined variables or invalid method calls fail the check. For details, see the PHPStan baseline guide.

Step 5: Integrating PHPStan into Continuous Integration

Run PHPStan automatically on every commit and pull request. If developers have to remember to run it by hand, regressions will slip through when someone skips that step.

Add the check to your continuous integration platform. For GitHub Actions, put the following workflow in .github/workflows/phpstan.yml:

The PHP 8.3 runner below is an example. Choose a PHP version supported by your application and the PHPStan release in composer.lock.

name: Static Analysis

on:
    push:
        branches: [ main, develop ]
    pull_request:
        branches: [ main, develop ]

jobs:
    phpstan:
        name: PHPStan Quality Gate
        runs-on: ubuntu-latest

        steps:
            - name: Check out repository
              uses: actions/checkout@v4

            - name: Set up PHP runtime
              uses: shivammathur/setup-php@v2
              with:
                  php-version: '8.3'
                  coverage: none
                  tools: composer:v2

            - name: Get Composer cache directory
              id: composer-cache
              run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT

            - name: Cache Composer dependencies
              uses: actions/cache@v4
              with:
                  path: ${{ steps.composer-cache.outputs.dir }}
                  key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
                  restore-keys: ${{ runner.os }}-composer-

            - name: Install Composer dependencies
              run: composer install --prefer-dist --no-progress --no-interaction

            - name: Cache PHPStan result cache
              uses: actions/cache@v4
              with:
                  path: var/cache/phpstan
                  key: ${{ runner.os }}-phpstan-${{ github.sha }}
                  restore-keys: ${{ runner.os }}-phpstan-

            - name: Run PHPStan analysis
              run: vendor/bin/phpstan analyse --error-format=github --no-progress

Essential CI Optimization Rules

Three settings matter for the speed and reliability of this workflow:

  1. Cache the PHPStan result cache: PHPStan uses an internal cache stored in tmpDir (var/cache/phpstan in our example). Reusing this directory across CI runs can speed up later analysis; the gain depends on which files and dependencies changed.
  2. Use GitHub error formatting: Adding --error-format=github causes PHPStan to output annotations directly inside GitHub pull request diffs, so reviewers can see the affected lines.
  3. Never generate or overwrite baselines inside CI: The CI pipeline must run read-only analysis. Generating a baseline inside CI hides failures and lets broken code enter the main branches.
A green sequence of checks on a workstation monitor illustrates a passing analysis job in CI.

Step 6: Worked Example: Fixing Bugs and Shrinking the Baseline

This invoice calculator has an uninitialized variable that triggers a runtime warning for certain coupon values:

<?php

namespace App\Billing;

class InvoiceCalculator
{
    /**
     * Calculate final invoice total with regional discounts.
     */
    public function calculateTotal(float $subtotal, ?string $couponCode): float
    {
        if ($couponCode === 'WINTER20') {
            $discount = $subtotal * 0.20;
        } elseif ($couponCode === 'VIP50') {
            $discount = $subtotal * 0.50;
        }

        return $subtotal - $discount;
    }
}

At Level 1, PHPStan flags this method because $discount is undefined whenever $couponCode is null or does not match either specific coupon:

Line 17: Variable $discount might be undefined.

The initial baseline records this error in phpstan-baseline.neon. CI can still catch new errors at the chosen level.

While working on a billing ticket, an engineer initializes the discount before checking the coupon:

<?php

namespace App\Billing;

class InvoiceCalculator
{
    /**
     * Calculate final invoice total with regional discounts.
     */
    public function calculateTotal(float $subtotal, ?string $couponCode): float
    {
        $discount = 0.0;

        if ($couponCode === 'WINTER20') {
            $discount = $subtotal * 0.20;
        } elseif ($couponCode === 'VIP50') {
            $discount = $subtotal * 0.50;
        }

        return $subtotal - $discount;
    }
}

With the variable initialized, the error no longer occurs.

Two workstation screens contrast a crowded red error diagram with a smaller green flow after a fix.

Updating the Baseline File

When an ignored error disappears from your code, PHPStan reports an unmatched ignored error by default. It warns you that an error recorded in the baseline was not triggered during analysis:

Ignored error pattern '#^Variable \$discount might be undefined\.$#' was not matched in reported errors.

This check keeps obsolete rules out of the baseline. To remove the entry for the error you fixed, run:

vendor/bin/phpstan analyse --generate-baseline

On PHPStan 2.3.5 or later, --fix can also remove unmatched baseline entries, as described in the command-line reference:

vendor/bin/phpstan analyse --fix

Review the resulting diff: --fix can apply other supported code fixes too. Commit the updated baseline alongside the refactored code. The baseline then records the reduction.

Step 7: When and How to Raise the Rule Level

Once the team is comfortable working at Level 0 or Level 1 and the baseline size is stable, plan to raise the level. The baseline lets you introduce stricter checks without requiring everyone to stop feature work and fix all the newly reported errors at once.

Handle each increase in its own branch:

  1. Create a dedicated technical debt branch: Never mix rule level upgrades with feature pull requests. Isolate the configuration change on a clean branch.
  2. Increase the level in phpstan.neon: Bump the level parameter by exactly one (for example, from level 1 to level 2).
  3. Evaluate the new diagnostics: Run vendor/bin/phpstan analyse after changing the level to see which checks now report errors. The existing baseline remains included through phpstan.neon.
  4. Categorize the findings: If the new level reports only 20 or 30 errors, fix them directly on the branch and submit a pull request. If it reports 800 errors, regenerate the baseline at the new level using vendor/bin/phpstan analyse --generate-baseline.
  5. Merge the updated baseline: Merging the regenerated baseline locks in the higher level checks for all future code without delaying other developers.

Recommended Progression Milestones

You can group the rule levels into four phases when planning the work:

  • Phase 1 (Levels 0 to 2): Focuses on basic sanity, undefined variables, and valid method calls. This phase eliminates runtime crashes and catches silent typos in class and method names.
  • Phase 2 (Levels 3 to 5): Introduces type consistency. Ensures functions return what they claim to return and verifies argument types passed to methods. Adopting these levels pairs effectively with modern PHP features like typed properties, as outlined in our overview of PHP 8.5 features.
  • Phase 3 (Levels 6 to 7): Reports missing type information, then checks operations that are valid for only some members of a union type.
  • Phase 4 (Levels 8 to 10): Full type safety and null defensiveness. Eliminates null pointer exceptions and enforces strict handling across mixed types.

Document the conventions so developers across the team know how to handle analysis failures and baseline changes. Use the technical writing rules to keep onboarding documentation and PR review standards easy to follow.

Common Mistakes to Avoid

  • Committing developer-specific configurations with local absolute paths: Saving machine-specific file paths or environment directories in phpstan.neon breaks analysis for other team members and remote CI runners. Commit a version-controlled phpstan.neon.dist containing project-relative paths for the team, and place any uncommitted local phpstan.neon overrides in .gitignore.
  • Failing to commit composer.lock to pin the PHPStan version: Letting PHPStan versions float across developer workstations and CI pipelines introduces unexpected build failures. PHPStan frequently refines its type inference and introduces stricter diagnostics in minor releases. Committing composer.lock guarantees that every developer and automated CI runner executes the exact same analyzer release.
  • Disabling unmatched error reporting: Setting reportUnmatchedIgnoredErrors: false allows obsolete entries to linger in your baseline forever. Keep this setting enabled so your baseline naturally shrinks as code is refactored.
  • Analyzing under mismatched PHP runtime versions: PHPStan evaluates core library signatures, language syntax, and deprecations based on the active PHP binary unless instructed otherwise. If developers run analysis on PHP 8.3 locally while production servers run on PHP 8.1, the analyzer misses code that fails in production. Set the phpVersion parameter explicitly in phpstan.neon.dist to guarantee analysis matches your production target.
  • Modifying the baseline carelessly: Manual edits are supported, but check the pattern and count against the current diagnostic. Regenerating the baseline can also add unrelated new errors, so review its diff before committing.

Frequently Asked Questions

What is the difference between a baseline and ignoreErrors?

Both suppress reported errors. The difference is what you want to keep track of.

The ignoreErrors array in phpstan.neon is designed for deliberate exceptions where you know the code is intentional, such as working around third-party libraries that lack complete typing stubs. These rules apply across all matching files in the project.

PHPStan generates phpstan-baseline.neon to track existing errors. It records file paths, regex error patterns, and occurrence counts. When you fix an error, update the baseline so its count falls or its entry disappears. An occurrence beyond the recorded count will be reported.

How should teams handle dynamic properties in legacy code?

PHP 8.2 deprecated dynamic properties. If a legacy class intentionally has undeclared attributes, describe those properties with PHPDoc so PHPStan can analyze their types:

/**
 * @property string $customFieldValue
 */
class LegacyEntity
{
}

Class-level @property tags describe the dynamic schema to PHPStan. You can add them without rewriting the database abstraction.

Why does PHPStan run out of memory on large codebases?

Building an abstract syntax tree and tracking variable type unions across thousands of source files takes a lot of RAM. By default, PHPStan respects PHP CLI memory limits, which may be set to 128MB or 512MB in standard configurations.

Increase the memory limit during analysis by passing the --memory-limit CLI flag:

vendor/bin/phpstan analyse --memory-limit=2G

Set a limit that fits the CI worker's available memory. If the process still runs out of memory, check the analyzed paths and PHPStan's troubleshooting guidance before increasing it again.

Can PHPStan analyze template files and framework magic?

PHPStan does not inspect template files such as Twig or Blade templates directly. Analyzing template files requires separate tooling, such as dedicated template linters or tools that compile templates into checked PHP code before analysis.

Framework extensions instead help PHPStan understand dynamic PHP framework APIs that standard static inspection cannot resolve without runtime context. These extensions provide reflection data and type-narrowing rules for dependency injection containers, Doctrine query builders, repository return types, and dynamic model magic like active record properties. Official extensions maintained in the PHPStan extension library include phpstan-symfony for Symfony service containers and controllers, phpstan-doctrine for Doctrine entity managers and object queries, and phpstan-phpunit for PHPUnit mock objects and assertions. For Laravel applications, the community-maintained Larastan package (larastan/larastan) supplies the reflection extensions and stubs needed to understand Eloquent model attributes, relations, and query scopes.