Skip to content
Efficience IT

Need an outside perspective on your project?

Contact us
FR
·8 min read·Code qualityRecently updated

PHP Static Analyzers: PHPStan, Deptrac, Rector Compared

By Louis-Arnaud Catoire

Updated on

PHP Static Analyzers: PHPStan, Deptrac, Rector Compared

A serious PHP project always ends up accumulating analysis tools: a phpstan.neon file, a .php-cs-fixer.dist.php, a rector.php, sometimes a deptrac.yaml. Each answers a different question, and that is precisely what creates the confusion. Many teams install two tools that overlap and forget the one they would really miss.

This article compares the main PHP static analysis tools, says what each one does and does not do, and proposes a realistic adoption order for a Symfony project.

What we mean by static analysis

A static analyzer reads the source code without running it. It builds a representation of the program, then applies rules to it. Depending on the rules, it looks for three very different things:

  • bugs: a call to a nonexistent method, an unhandled null value, an inconsistent return type;
  • style: indentation, use order, braces, naming conventions;
  • structure: dependencies between layers, complexity, dead code.

Comparing these tools as if they were competitors is therefore misleading. Most of them do not replace each other, they complement each other.

PHPStan: the bug detector

PHPStan is the reference tool for detecting typing and logic errors. It offers eleven strictness levels, from 0 to 10, which lets you adopt the tool gradually on an existing codebase. We detailed the setup in our PHPStan guide and what is new in version 2 in the article on PHPStan 2.0.

Its strengths:

  • a baseline that freezes existing errors and blocks only new ones;
  • official extensions for Symfony, Doctrine, and PHPUnit, which understand the service container and repositories;
  • customizable rules to encode a team's conventions.
parameters:
    level: 6
    paths:
        - src
includes:
    - phpstan-baseline.neon

Its limit: it says nothing about style and nothing about architecture. Perfectly typed code can mix Doctrine and business logic without PHPStan complaining.

Psalm: the alternative that overlaps with PHPStan

Psalm plays on the same field as PHPStan. It also offers levels, a baseline, and an annotation system for complex types. It highlights data flow analysis (taint analysis), which is useful for spotting SQL or XSS injections.

In practice, the two tools find very similar errors. Running them together doubles CI time and false positives, for little gain. Our recommendation is to pick one of the two: PHPStan in the vast majority of cases, thanks to its extension ecosystem and its community. Psalm remains relevant if taint analysis is an explicit requirement.

Need support on your project?

Let's talk

PHP-CS-Fixer: the end of style debates

PHP-CS-Fixer looks for no bugs. It rewrites the code so that it follows a standard, for example PSR-12 or the @Symfony ruleset. Its value is human: as long as a tool settles the question, nobody comments on indentation in code review anymore.

<?php

$finder = (new PhpCsFixer\Finder())->in(__DIR__ . '/src');

return (new PhpCsFixer\Config())
    ->setRules(['@Symfony' => true, 'declare_strict_types' => true])
    ->setFinder($finder);

It runs in --dry-run mode in CI to fail on a deviation, and in fix mode locally or in a pre-commit hook. It complements a team's coding conventions by making them executable rather than documentary.

Deptrac: the architecture guardrail

Deptrac answers a question that neither PHPStan nor PHP-CS-Fixer asks: is this class allowed to use that other one? You declare layers (Domain, Application, Infrastructure) and the dependencies allowed between them. Deptrac fails as soon as a rule is violated.

deptrac:
  paths:
    - ./src
  layers:
    - name: Domain
      collectors:
        - type: directory
          value: src/Domain/.*
    - name: Infrastructure
      collectors:
        - type: directory
          value: src/Infrastructure/.*
  ruleset:
    Domain: ~
    Infrastructure:
      - Domain

Here, the Domain depends on nothing, and the Infrastructure may depend on the Domain. A use Doctrine\ORM\... slipped into the Domain breaks the build. This is exactly the principle defended in why your Domain should never know about Symfony, and a natural complement to a hexagonal architecture: without automatic checks, boundaries erode within a few months.

Rector: refactoring in place of developers

Rector does not report problems, it fixes them. It applies code transformation rules: PHP version upgrades, attribute migrations, replacing deprecated APIs. We cover it in detail in the article dedicated to Rector.

It is the most worthwhile tool during a version upgrade, because it turns hundreds of mechanical changes into a single diff review. It is also useful for tackling technical debt at an industrial scale rather than by hand. A word of caution: always run it on a clean branch, with the tests green before and after.

Mago: a single binary for several of these roles

Mago is a PHP toolchain written in Rust, licensed under MIT or Apache-2.0. It is a single binary, with no PHP runtime, that bundles four commands: mago fmt for formatting, mago lint for style and best-practice rules, mago analyze for type analysis and mago guard for architecture rules. It therefore partly overlaps with PHP-CS-Fixer, PHPStan and Deptrac.

A mago.toml file, generated by mago init, is enough to get started:

php-version = "8.4"

[source]
paths = ["src"]

On a method that passes a ?string to strtoupper(), mago analyze reports a possibly-null-argument error. Like PHPStan, it can freeze the existing errors: mago analyze --generate-baseline --baseline analysis-baseline.toml records the current errors, then mago analyze --baseline analysis-baseline.toml only reports the new ones.

mago guard follows the same principle as Deptrac. With the rule below, a use or an extends from the App\Domain\ namespace to the infrastructure makes the command fail:

[[guard.perimeter.rules]]
namespace = "App\\Domain\\"
permit = ["@self", "@native"]

The project is young and its ecosystem is still smaller than PHPStan's. The analyzer documentation does not mention an equivalent of the PHPStan extensions that understand the Symfony service container and Doctrine repositories. The linter does offer rule sets you can enable for Symfony and PHPUnit, with integrations = ["symfony", "phpunit"]. The analysis, baseline and guard examples above were run with Mago 1.57.0.

Mago versus PHPStan: our measurements

The Mago documentation claims that an entire project is analyzed in a few seconds. We checked it on the src/ folder of a real Symfony 8 application, with PHPStan at level 10 and Mago's default configuration, with no baseline on either side to compare on equal terms.

ToolRoleTime
PHPStan, cold cacheType analysis15.6 s
PHPStan, warm cacheType analysis3.9 s
mago analyzeType analysis4.7 s
mago lintStyle and best practices1.1 s
PHP-CS-Fixer (--dry-run)Style6 s

Mago has no result cache: every run is a cold run, and it is still more than three times faster than a cold PHPStan. It is close to PHPStan with a warm cache, with nothing to warm up or invalidate. The gain is most visible in CI, where the cache is often missing. The linter runs five times faster than PHP-CS-Fixer.

As for the results, the numbers are not directly comparable, because each tool applies its own rules:

  • PHPStan level 10: 446 errors.
  • mago analyze: 220 errors, 229 warnings and 115 suggestions, 564 reports in total.
  • mago lint: 140 errors, 456 warnings, 2 notes and 113 suggestions, 98 of them automatically fixable. PHPStan has no direct equivalent.

Mago therefore reports more, but it grades what it finds: only 220 errors are of the same nature as PHPStan's, the rest is nuance. This volume proves neither that it finds more real bugs nor that it misses some: you have to sort both lists to know. These measurements come from a single project and a single machine, so run them again on your own code.

Our recommendation: on a Symfony project that already uses PHPStan and its extensions, do not replace anything right away. Try Mago alongside them in CI, without making it blocking, to compare what it finds more or less of. On a new project, or to reduce the number of tools to maintain, it deserves a real evaluation.

PHPMD, PHPMetrics, and the others

A few tools complete the picture:

  • PHPMD spots signs of poor design: methods that are too long, too many parameters, high cyclomatic complexity. Its rules partly overlap with the higher PHPStan levels and with code review.
  • PHPMetrics produces a visual maintainability report. It is used to make a diagnosis during an audit, less to block a CI.
  • Infection measures the quality of your tests through mutation testing, which is a different topic from static analysis but is installed the same way.

To track down what is no longer called, dead code analyzers are part of the approach described in our project retrospective on dead code elimination.

Comparison table

ToolDetectsFixes on its ownAdoption
PHPStanBugs, typesNoGradual, by levels
PsalmBugs, types, taintPartiallyGradual
PHP-CS-FixerStyle deviationsYesImmediate
DeptracArchitecture violationsNoAfter defining the layers
RectorCode to modernizeYesIn batches of rules
MagoBugs, types, style, architecturePartiallyGradual, with a baseline
PHPMDComplexity, designNoOptional

In which order to install them

On an existing project, a simple order limits friction:

  1. PHPStan at a low level with a baseline. The gain is immediate and no developer is blocked. You go up one level per sprint.
  2. PHP-CS-Fixer. A single reformatting pass, then the CI keeps the style clean. Make this commit on its own so it does not pollute the history.
  3. Rector, occasionally. Run it at each PHP or Symfony version upgrade, not continuously.
  4. Deptrac, once the layers are decided. There is no point installing it before the team has agreed on the target architecture.

On a new project, Mago can replace steps 1, 2 and 4 with a single tool, provided you accept a younger ecosystem.

In a CI, the first three fit in a few lines and run in parallel. What matters most is not the number of tools but that they are blocking: a warning that nobody reads has no value.

Key takeaways

There is no single best PHP static analyzer, because these tools do not answer the same question. PHPStan hunts for bugs, PHP-CS-Fixer settles style, Deptrac protects architecture, Rector modernizes, and Mago tries to combine several of these roles in a single binary. Choose one tool per question, make them blocking in CI, and raise the level of strictness gradually.

If you want an outside opinion on the quality pipeline of an existing Symfony project, it is a point we systematically examine during a code audit (in French).

Have a project in mind?

Our team replies within 48 hours to look at your needs and suggest a suitable approach.

Contact us

Frequently asked questions

PHPStan analyzes type consistency and detects bugs without running the code. PHP-CS-Fixer checks no logic: it reformats the code to apply a style standard like PSR-12. The two are complementary and both run in continuous integration.

On a single project, one of the two is enough. Both detect very similar families of errors. PHPStan now has the largest community and extension ecosystem, notably for Symfony and Doctrine, which makes it the default choice for most teams.

Deptrac checks architecture rules: which layer is allowed to call which other layer. PHPStan checks that the code is properly typed, not that the domain stays independent of the framework. Deptrac fails the CI if a forbidden dependency appears.

Start with PHPStan at a low level with a baseline, then PHP-CS-Fixer to remove style noise from reviews. Add Rector to automate version upgrades, and Deptrac once the team has defined the layers it wants to protect.

Mago bundles a formatter, a linter, a type analyzer and architecture rules in a single binary, so it overlaps with these three tools. It is younger, and its documentation does not mention an equivalent of the PHPStan extensions for Symfony and Doctrine. On an existing project, try it alongside your current tools before replacing anything.

Related articles