PHPStan and Psalm on a site built on includes

An older PHP site loads its functions with require_once and hands variables from one file to another with include: a page includes a file that sets $page_lang, then uses it. Neither PHPStan nor Psalm follows those includes. Run without a config, both report mostly the includes, not the code. This manual builds the two configs step by step on a three-file demo, then shows what they changed on a real site of 2,851 PHP files: PHPStan went from 14,248 findings to about 700, Psalm from 22,596 to about 2,700.

Tools used here: PHPStan 2.3.7, Psalm 7.18.0, PHP 8.5 and Docker with the php:8.5-cli image, Bash. How PHPStan finds classes in hidden folders is in PHPStan without an autoloader.

Demo layout

The docroot is src/. A hidden folder src/.php/ holds a helper function and a file of page variables; the page includes both.

src/ ├── .php/ │ ├── helpers.php │ └── vars.php └── blog/ └── index.php

src/.php/helpers.php

<?php function site_img($src, $alt) { return '<img src="' . $src . '" alt="' . $alt . '">'; }

src/.php/vars.php

<?php $page_lang = 'en'; $page_title = 'Blog';

src/blog/index.php

<?php $root = $_SERVER['DOCUMENT_ROOT']; require_once($root . '/.php/helpers.php'); include($root . '/.php/vars.php'); function page_footer() { return '<footer>' . $page_title . '</footer>'; } echo '<html lang="' . $page_lang . '"><h1>' . $page_title . '</h1>'; echo site_img('/blog/img/cover.jpg', $page_title); echo page_footer();

The page has one real bug: page_footer() reads $page_title, but a function does not see the variables of the file around it, so the footer is empty and PHP warns Undefined variable $page_title. Every other variable the page uses is set by vars.php.

Run both tools in Docker

No Composer and no PHP on the host: download both phar files once and run them in the official PHP image. Create a folder for them:

mkdir -p ~/.cache/php-tools

Download PHPStan 2.3.7 and Psalm 7.18.0:

curl -sSLo ~/.cache/php-tools/phpstan.phar https://github.com/phpstan/phpstan/releases/download/2.3.7/phpstan.phar

curl -sSLo ~/.cache/php-tools/psalm.phar https://github.com/vimeo/psalm/releases/download/7.18.0/psalm.phar

Two shell functions mount the current folder as /app and the phar folder read-only as /tools. Run them from the project root, the folder that holds src/:

phpstan() { docker run --rm -v "$PWD:/app" -w /app -v "$HOME/.cache/php-tools:/tools:ro" php:8.5-cli php /tools/phpstan.phar "$@"; }

psalm() { docker run --rm -v "$PWD:/app" -w /app -v "$HOME/.cache/php-tools:/tools:ro" php:8.5-cli php /tools/psalm.phar "$@"; }

First: enough memory

Before any config, a large site can stop PHPStan altogether. PHPStan analyses in parallel workers, and each one gets the PHP default of 128 MB. On the site of 2,851 files the run ended like this:

⚠️ Result is incomplete because of severe errors. ⚠️ Fix these errors first and then re-run PHPStan to get all reported errors. Error -- -------------------------------------------------------------------------- Child process error: PHPStan process crashed because it reached configured PHP memory limit: 128M Increase your memory limit in php.ini or run PHPStan with --memory-limit CLI option. while running parallel worker -- -------------------------------------------------------------------------- [ERROR] Found 1 error

Found 1 error is the crash, not a finding: nothing was analysed. A script that only reads the exit code or the last line sees one error and goes on. Give the workers more memory on every run:

phpstan analyse --memory-limit=2G src/

With 2 GB the same site was analysed in full. The demo is small enough for the default, so the commands below leave the option out.

PHPStan without a config

phpstan analyse --no-progress --level 1 src/blog/index.php

------ ---------------------------------------------------------------------- Line index.php ------ ---------------------------------------------------------------------- 9 Undefined variable: $page_title 🪪 variable.undefined 12 Variable $page_lang might not be defined. 🪪 variable.undefined 12 Variable $page_title might not be defined. 🪪 variable.undefined 13 Function site_img not found. 🪪 function.notFound 💡 Learn more at https://phpstan.org/user-guide/discovering-symbols 13 Variable $page_title might not be defined. 🪪 variable.undefined ------ ---------------------------------------------------------------------- [ERROR] Found 5 errors

Five findings, and one of them is the bug (line 9). PHPStan does not run the require_once, so site_img() is unknown, and it does not read vars.php, so every page variable might not be defined.

PHPStan: scanDirectories

scanDirectories makes PHPStan read definitions from a folder without reporting errors in it. The hidden folder is named on its own, because a folder walk skips folders whose name starts with a dot:

phpstan.neon

parameters: level: 1 scanDirectories: - src - src/.php

phpstan analyse --no-progress src/blog/index.php

Note: Using configuration file /app/phpstan.neon. ------ -------------------------------------------- Line index.php ------ -------------------------------------------- 9 Undefined variable: $page_title 🪪 variable.undefined 12 Variable $page_lang might not be defined. 🪪 variable.undefined 12 Variable $page_title might not be defined. 🪪 variable.undefined 13 Variable $page_title might not be defined. 🪪 variable.undefined ------ -------------------------------------------- [ERROR] Found 4 errors

The function is found. The variables are not: a scanned file gives PHPStan its functions and classes, never the variables it sets.

PHPStan: checkMaybeUndefinedVariables

PHPStan has two levels of certainty for a variable. Undefined variable means no path sets it; might not be defined means it cannot tell. On a page whose variables come from an include it can never tell, so turn the second kind off:

phpstan.neon

parameters: level: 1 checkMaybeUndefinedVariables: false scanDirectories: - src - src/.php

phpstan analyse --no-progress src/blog/index.php

Note: Using configuration file /app/phpstan.neon. ------ --------------------------------- Line index.php ------ --------------------------------- 9 Undefined variable: $page_title 🪪 variable.undefined ------ --------------------------------- [ERROR] Found 1 error

One finding left, and it is the bug.

Psalm with a minimal config

Psalm needs a config file to know which files are the project:

psalm.xml

<?xml version="1.0"?> <psalm errorLevel="4" xmlns="https://getpsalm.org/schema/config"> <projectFiles> <directory name="src" /> </projectFiles> </psalm>

psalm --no-cache --no-progress --monochrome

ERROR: UnusedVariable - src/.php/vars.php:3:1 - $page_lang is never referenced or the value is not used (see https://psalm.dev/077) ERROR: UnusedVariable - src/.php/vars.php:4:1 - $page_title is never referenced or the value is not used (see https://psalm.dev/077) ERROR: UndefinedVariable - src/blog/index.php:9:25 - Cannot find referenced variable $page_title (see https://psalm.dev/024) ERROR: UndefinedGlobalVariable - src/blog/index.php:12:23 - Cannot find referenced variable $page_lang in global scope (see https://psalm.dev/127) ERROR: UndefinedGlobalVariable - src/blog/index.php:12:47 - Cannot find referenced variable $page_title in global scope (see https://psalm.dev/127) ERROR: UndefinedFunction - src/blog/index.php:13:6 - Function site_img does not exist, consider enabling the allFunctionsGlobal config option if scanning legacy codebases (see https://psalm.dev/021) 6 errors found

Psalm walks hidden folders by itself, so it reads vars.php too, and reports the same include problem three ways: the variables of vars.php are never used there (UnusedVariable), the page uses variables it never set (UndefinedGlobalVariable), and the function is unknown (UndefinedFunction). The bug is the UndefinedVariable on line 9.

Psalm: allFunctionsGlobal and findUnusedCode

Psalm counts a function as defined only when the file that defines it is included in a way it can follow; the error message itself names the option for older code. findUnusedCode="false" stops the unused-code checks, which on such a site flag every variable a file sets for the page that includes it:

psalm.xml

<?xml version="1.0"?> <psalm errorLevel="4" allFunctionsGlobal="true" findUnusedCode="false" xmlns="https://getpsalm.org/schema/config"> <projectFiles> <directory name="src" /> </projectFiles> </psalm>

psalm --no-cache --no-progress --monochrome

ERROR: UndefinedVariable - src/blog/index.php:9:25 - Cannot find referenced variable $page_title (see https://psalm.dev/024) ERROR: UndefinedGlobalVariable - src/blog/index.php:12:23 - Cannot find referenced variable $page_lang in global scope (see https://psalm.dev/127) ERROR: UndefinedGlobalVariable - src/blog/index.php:12:47 - Cannot find referenced variable $page_title in global scope (see https://psalm.dev/127) ERROR: UndefinedGlobalVariable - src/blog/index.php:13:38 - Cannot find referenced variable $page_title in global scope (see https://psalm.dev/127) 4 errors found

Psalm: suppress UndefinedGlobalVariable

The three findings left besides the bug are the page variables. Psalm has no option to follow includes, so turn the check off with an issue handler. UndefinedVariable, the one inside a function, stays on:

psalm.xml

<?xml version="1.0"?> <psalm errorLevel="4" allFunctionsGlobal="true" findUnusedCode="false" xmlns="https://getpsalm.org/schema/config"> <projectFiles> <directory name="src" /> </projectFiles> <issueHandlers> <!-- Variables of a page that an included file sets. --> <UndefinedGlobalVariable errorLevel="suppress" /> </issueHandlers> </psalm>

psalm --no-cache --no-progress --monochrome

ERROR: UndefinedVariable - src/blog/index.php:9:25 - Cannot find referenced variable $page_title (see https://psalm.dev/024) return '<footer>' . $page_title . '</footer>'; ------------------------------ 1 errors found

The bug both tools kept

Both configs leave exactly the finding that is a bug. Pass the title to the function instead of reading it from the file around it:

src/blog/index.php

function page_footer($title) { return '<footer>' . $title . '</footer>'; }

and call it as page_footer($page_title). Both tools are then clean:

phpstan analyse --no-progress src/blog/index.php

Note: Using configuration file /app/phpstan.neon. [OK] No errors

psalm --no-cache --no-progress --monochrome

------------------------------ No errors found! ------------------------------

On a site of 2,851 files

The same configs on an imported travel site: 2,851 PHP files, pages built from numbered header and footer includes, and helper functions in hidden folders, one copy per language. Level 1 for PHPStan, error level 4 for Psalm:

no configwith the configs
PHPStan14,248: 9,408 might not be defined, about 4,500 unknown functions and classesabout 700
Psalm22,596: 9,001 UnusedVariable, 6,204 UndefinedGlobalVariable, 4,421 UndefinedFunctionabout 2,700

What was left was worth reading:

  1. 547 includes of files that do not exist (PHPStan Path in include() ... is not a file, Psalm MissingFile): a page that includes a missing footer gets a warning and an unfinished page.
  2. 34 calls of a page class constructor with an unknown or a missing named argument. Each one is a fatal error at runtime; one of them had already been found by hand on a page that died half-way.
  3. about 1,400 dynamic properties in Psalm (UndefinedThisPropertyAssignment and the fetches that go with it): deprecated since PHP 8.2.
  4. about 170 tainted outputs and headers from Psalm's taint analysis: input that reaches the HTML without escaping.

What the configs hide

  1. A page variable that is used before the include that sets it, or that no include sets at all, is no longer reported at file level. Inside a function it still is.
  2. With allFunctionsGlobal, a function defined in several files (one copy per language, each with its own parameters) is known to Psalm by one of its definitions. Calls that match another copy are reported as TooManyArguments: check the copy the page really includes before changing the call.
  3. The configs do not follow a path built at runtime. An include path made from $_SERVER['DOCUMENT_ROOT'] is checked against the files only when the tool can resolve it.

Article author: Klavdiya Kondakova