Skip to content
Tutorials Center
My learning

Topics

Lesson 127 of 147 ยท Modern PHP and Ecosystem

Static Analysis and Code Quality

Find PHP bugs before running the code: how static analyzers like PHPStan and Psalm work, what their levels mean, how to annotate types and enforce style.

PHP is a dynamic language: most mistakes show up only when the faulty line actually runs. A typo in a method name, a function that sometimes returns null, an array key that doesn't exist, all of these wait quietly in your code until a user hits that path in production. Tests catch many of them, but only on the paths they exercise.

Static analysis reads your code without running it and reasons about it, much like a compiler would in a statically typed language. It reports the call to a method that doesn't exist, the null you forgot to handle and the string you passed where an int is required. Combined with a code-style fixer and a few conventions, it is the cheapest quality investment a PHP project can make.

This lesson explains what analyzers do, how to describe types they can't infer, how analysis levels work and how to adopt a tool in an existing code base. It builds on the type system and type declarations, and fits in the workflow described in Coding Standards and Testing.

What an analyzer actually does

An analyzer parses every file into a tree, resolves classes, functions and constants, and then tracks the possible types of each expression as it follows the control flow. It reports anything that contradicts what it knows.

flowchart LR
  A["Source files"] --> B["Parser: syntax tree"]
  B --> C["Resolve classes<br/>and functions"]
  C --> D["Infer types along<br/>every code path"]
  D --> E["Compare with<br/>declared types"]
  E --> F["Report errors"]

An analyzer never executes your code; it builds a model of it and checks the model.

Look at this function. It runs fine on a good day and fails on a bad one:

PHP
<?php
function findUser(array $users, int $id): ?array
{
    return $users[$id] ?? null;
}

$user = findUser($all, 3);
echo strtoupper($user['name']);   // what if findUser returned null?

A static analyzer sees that $user may be null on the second-to-last line and reports that you access an offset on null. A test only fails if somebody writes the right test; the analyzer needs none.

The two big analyzers for PHP are:

  • PHPStan: focuses on finding bugs, with a gradual "level" system and a large ecosystem of extensions (Laravel, Symfony, Doctrine).
  • Psalm: similar goals, with extra features such as taint analysis (tracking untrusted data into dangerous sinks) and automatic fixing of some issues.

Others you will meet: Phan, Rector (which rewrites code rather than reporting) and your IDE's built-in inspections, which use the same ideas.

Install them with Composer as development dependencies, for example composer require --dev phpstan/phpstan, then run vendor/bin/phpstan analyse src. The command lines below are read-only here because the editor has no Composer.

A taste of how it works

You can build a toy version of the idea. This script "analyzes" a snippet by checking that every function it calls is defined somewhere. That is the same first step real tools take: resolve names, then compare:

PHP A toy analyzer: undefined function calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real analyzers do the same for classes, methods, properties, constants and, most importantly, types. They use a proper parser (the nikic/php-parser library) instead of regular expressions, so they handle every PHP syntax form correctly.

Types: what PHP knows and what you add

The more type information your code carries, the more the analyzer can check. Native type declarations are the foundation: parameter, return and property types, readonly, enums and union types. For the rest there are PHPDoc annotations, which the analyzer reads as types even though PHP ignores them at runtime.

The most important use is describing array shapes and generics, which native types cannot express:

PHP
<?php
/**
 * @param list<string> $names             a sequential array of strings
 * @param array<string, int> $scores      string keys, int values
 * @param array{id: int, email: string} $row   a fixed shape
 * @return non-empty-string
 */
function describe(array $names, array $scores, array $row): string
{
    return implode(', ', $names) . ' / ' . $row['email'];
}

Useful annotations include:

Annotation Meaning
list<T> Array with keys 0, 1, 2, โ€ฆ in order
array<K, V> Array with key type K and value type V
array{a: int, b?: string} Array with specific keys (b optional)
non-empty-string, positive-int, int<0, 100> Refined scalar types
class-string<Foo> A string naming Foo or a subclass
callable(int): string A callable with a signature
@template T A generic type parameter (for collections and containers)

Generics deserve a closer look. PHP has no native generics, but a docblock can tell the analyzer that a collection holds a certain type:

PHP
<?php
/**
 * @template T
 */
final class Collection
{
    /** @param list<T> $items */
    public function __construct(private array $items) {}

    /** @return T|null */
    public function first(): mixed
    {
        return $this->items[0] ?? null;
    }
}

/** @var Collection<User> $users */
$users = new Collection([new User('Ada')]);
$users->first()?->name;   // the analyzer knows this is User|null

PHP itself still enforces only the native types, so docblock types are checked only by the tool. The next demo makes this difference tangible. A native type is enforced at runtime, a docblock type is not:

PHP Native types versus docblock types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The negative count passes PHP's own type check and fails only deep inside str_repeat(), yet a tool that understands positive-int flags it at the call site. That is the value of richer types: they move errors from runtime to your editor.

Levels: adopt it gradually

Pointing an analyzer at a ten-year-old project can produce thousands of errors. The tools solve this with levels. PHPStan has levels 0 to 10; each level adds checks on top of the previous ones:

Level Roughly checks
0 Basics: unknown classes, functions, methods called on $this, wrong argument counts
1โ€“2 Possibly undefined variables, unknown methods on all expressions, PHPDoc validity
3โ€“4 Return types, property types, dead code and always-true conditions
5 Argument types passed to functions
6 Missing type hints
7 Partially wrong union types
8 Calls on nullable values
9 Strict handling of the mixed type
10 Treats implicit mixed as an error too

Psalm uses levels 8 (most lenient) down to 1 (strictest) the other way around, so check which direction the tool counts. The exact list of checks evolves between versions; consult the tool's documentation.

The recommended path:

  1. Start at a low level so the first run is clean or nearly clean.
  2. Commit a baseline file: a snapshot of today's known errors, which the tool ignores. New code must be clean; old problems are paid off gradually.
  3. Raise the level step by step, fixing the new errors each time.
  4. Run the tool in CI so a pull request that adds errors fails.

A typical configuration file for PHPStan (phpstan.neon) looks like this:

NEON
parameters:
    level: 6
    paths:
        - src
        - tests
    excludePaths:
        - src/Legacy
includes:
    - phpstan-baseline.neon

Generate the baseline with vendor/bin/phpstan analyse --generate-baseline.

When the tool is wrong or you know better, you can suppress a single error with an annotation such as /** @phpstan-ignore-next-line */ or @psalm-suppress. Treat these as debt: add a comment explaining why, and prefer fixing the types.

Common findings and how to fix them

Most reports fall into a handful of families:

  • Possibly null. Fix by checking: if ($user === null) { throw ... }, or use ?-> when null is acceptable.
  • Array offset may not exist. Use ?? defaults, isset(), or declare the shape (array{id: int}) so the tool knows the key is there.
  • Mixed types. Values from json_decode(), $_POST or a database are mixed. Validate and narrow them (is_string(), filter_var()) before use.
  • Wrong return type. The function declared string but a branch returns null or false.
  • Dead code. A condition that is always true or a catch for an exception that can't be thrown.

The narrowing idea is central. After a check such as is_int($x), the analyzer treats $x as an int inside the branch:

PHP Narrowing types with checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each branch removes possibilities. By the last line only string remains, so strlen() is safe. A tool at a high level will refuse code that skips those checks.

Code style: a different kind of quality tool

Static analyzers check meaning. Code style fixers check formatting: brace positions, spacing, import order, trailing commas. The popular choices are PHP CS Fixer, PHP_CodeSniffer (phpcs/phpcbf) and Laravel Pint (a wrapper around PHP CS Fixer with sensible presets). They follow the community standards PSR-1 and PSR-12 (and the newer PER Coding Style).

The key benefit is not beauty but noise reduction: with an automatic fixer, code reviews stop arguing about style, and diffs only contain real changes.

Here is a miniature fixer that enforces two rules, so you can see what such tools do (they apply hundreds of rules on a real syntax tree):

PHP A toy code-style fixer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

(The first block prints spaces as dots so you can see the trailing whitespace.)

A quality pipeline

Put the tools together so each runs automatically:

flowchart LR
  A["git commit"] --> B["Pre-commit:<br/>style fixer on changed files"]
  B --> C["git push"]
  C --> D["CI pipeline"]
  D --> E["Style check"]
  D --> F["Static analysis"]
  D --> G["Tests"]
  E --> H{"All green?"}
  F --> H
  G --> H
  H -->|"yes"| I["Merge"]
  H -->|"no"| J["Fix and push again"]

Style, static analysis and tests run on every push; any red result blocks the merge.

A composer.json scripts section keeps the commands short and the same for everyone:

JSON
{
  "scripts": {
    "analyse": "phpstan analyse --memory-limit=1G",
    "style": "pint --test",
    "test": "pest",
    "ci": ["@style", "@analyse", "@test"]
  }
}

Then composer ci runs all three locally, and your CI server runs the same command.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What distinguishes static analysis from running your tests?

    An analyzer builds a model of the code and checks it. It can flag problems on paths that no test covers, though it does not replace tests.
  2. 2. What does the docblock @param list<string> $names add that the native type array cannot express?

    Native types stop at array. The docblock describes the contents, which only the analyzer reads; PHP does not enforce it.
  3. 3. You run PHPStan on a large legacy project and get 3,000 errors. What is the usual strategy?

    Baselines and levels let you adopt the tool gradually without a huge up-front clean-up.
  4. 4. After if (is_int($value)) { ... }, what does the analyzer assume about $value inside the braces?

    Type checks narrow the type inside the branch, which is why validating mixed input makes the code analyzable.
  5. 5. What is the main job of a tool such as PHP CS Fixer or Laravel Pint?

    Style fixers rewrite formatting. They do not check semantics; that is the analyzer's job.

Summary

  • Static analysis checks code without running it, finding undefined names, null misuse and type mismatches that tests may miss.
  • PHPStan and Psalm are the standard analyzers; both are installed with Composer and configured per project.
  • Native types are enforced by PHP; docblock types (list<T>, array{...}, positive-int, @template) are read only by the analyzer but make its checks far stronger.
  • Levels and baselines let you adopt analysis gradually and keep new code strict.
  • Narrow mixed values with checks like is_int() before using them.
  • Style fixers (PHP CS Fixer, PHP_CodeSniffer, Pint) remove formatting debates; run style checks, analysis and tests in CI.

Next: Project: To-Do List