orisai / phpstan-spaghetti
Teaches PHPStan to follow your includes, so legacy scripts stop being a bowl of mixed
Package info
github.com/orisai/phpstan-spaghetti
Type:phpstan-extension
pkg:composer/orisai/phpstan-spaghetti
Requires
- php: 7.4 - 8.6
- orisai/phpstan-trace: 1.x-dev
- phpstan/phpstan: ^2.3.6
Requires (Dev)
- brianium/paratest: ^6.3.0
- nikic/php-parser: ^5.9.0
- orisai/coding-standard: ^3.0.0
- orisai/phpstan-nette: 1.x-dev
- phpstan/extension-installer: ^1.4.0
- phpstan/phpstan-deprecation-rules: ^2.0.5
- phpstan/phpstan-phpunit: ^2.0.6
- phpstan/phpstan-strict-rules: ^2.1.1
- phpunit/phpunit: ^9.5.0
- shipmonk/dead-code-detector: ^0.15.0 || ^1.4.2
- tomasvotruba/cognitive-complexity: ^1.0.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-29 21:17:23 UTC
README
PHPStan Spaghetti
Because $connection came from somewhere. PHPStan support for include/require in legacy scripts.
Experimental. Nothing is released, everything may change.
Legacy applications often consist of scripts which include each other: init.php sets up variables, header.php
reads them, a page script includes both and continues with what they defined. PHPStan analyses each of these files on
its own, so an included script sees its variables as mixed and possibly undefined, and the including script does
not see what the included one assigned.
This extension follows the includes. An included file is analysed with the variables of the places that include it, and an include statement continues with what the included file assigned, returned or whether it ended the script.
Installation
Install the extension into the same Composer project as PHPStan itself, so that the autoloader PHPStan loads knows the extension's classes when it builds its container:
composer require --dev orisai/phpstan-spaghetti:1.x-dev orisai/phpstan-trace:1.x-dev phpstan/extension-installer
Neither package has a release yet: the extension requires the tracing core orisai/phpstan-trace 1.x-dev, which
Composer installs only when your project allows it, by requiring it at 1.x-dev too (above) or with
"minimum-stability": "dev" and "prefer-stable": true. With a Nette application, orisai/phpstan-nette works alongside
it (the forms of an included file).
phpstan/extension-installer includes the configuration of the extension and of the core. Without the installer, include both yourself (the extension does not include the core: PHPStan rejects a file included twice, and every extension built on the core needs it):
includes: - vendor/orisai/phpstan-trace/extension.neon - vendor/orisai/phpstan-spaghetti/extension.neon
What it does
- Include paths built from literal strings,
__DIR__,__FILE__,dirname(), constants of adefine()orconstand class constants (Paths::Root,self::Root) in the analysed files, and variables holding a few literal strings, are followed; any other path is reported (orisai.spaghetti.includeNotDiscoverable). A relative path is resolved as PHP does:./and../from the working directory, any other one from the include path, then the including file's directory, then the working directory. - An
include_once/require_onceof a file included on every path before is a no-op (true); of a file included on some paths it maybe runs (its value is1|true, what it assigns is possibly assigned); a file with a single include site is assumed to run there. - An include of a file that does not exist is reported (
orisai.spaghetti.includedFileNotFound; PHPStan's owninclude.fileNotFoundmay report it too):includegivesfalseand the script continues,requireends it. Where a path may hold several strings of which some name no file, those are reported (orisai.spaghetti.includedFilePossiblyNotFound):includemay givefalseand may change nothing,requiremay end the script. - A path only the scope resolves (a variable holding a few literal strings) is followed like a literal one: its files are included-only, get their entries from it and are typed before it.
- A conditional include (
include $admin ? 'admin.php' : 'user.php';,include __DIR__ . ($admin ? '/a.php' : '/b.php');, amatchof literal arms, or a variable a branch, aswitch,?:or??gave a few literal strings) includes one of its targets: each target gets the site's variables and its header is checked at the site, and after the include the including code continues with the join of the targets' results (a variable only one target assigns is possibly assigned). After such aninclude_onceorrequire_once, a later_onceinclude of one of the targets maybe runs. A path of more than 32 strings, or one that may also hold something else than a literal string, is reported as not discoverable. - A file outside the analysed paths (excluded by
excludePaths, inscanDirectories, invendor/, or with an extension PHPStan does not analyse) is not followed: what it does is ignored and its value ismixed. Only its header counts: its@vartags are checked at the include sites, and its@var-outtags are what the includer sees afterwards (without them, the includer's variables are unchanged by it). An include of such a file containing PHP code is reported (orisai.spaghetti.includedFileNotAnalysed: "Included file vendor/lib/x.php is outside the analysed paths: what it does is not followed."), with a header or without; a file of plain HTML or text, with no PHP code, does nothing and is not reported, nor is Composer'sautoload.phpin the project's vendor directory (config.vendor-dirofcomposer.json,COMPOSER_VENDOR_DIR). - An included file starts with the variables of all its include sites: their types are unioned, and a variable missing
at some site is possibly undefined. The types are PHPDoc types, as if a
@vartag declared them: PHP guarantees nothing natively about them, sotreatPhpDocTypesAsCertainapplies to them, and an inline@varis checked against them as against any PHPDoc type (varTag.type). - After an include statement, the variables the included file assigned have the types it left them with when it ran
with this site's variables (each site gets its own result, as PHP runs the file with them), the include
expression has the type of the file's
return(1without one), and an include of a file which always ends the script (exit(), a never-returning call) ends the including code too. A variable the included file only tests (isset($flag),empty(),??) and nobody defined stays undefined, as in PHP. - The types are computed before the analysis, in PHPStan's main process, and cached under
tmpDirwith what they depend on: a run with no change builds nothing, and an edit parses the edited file and recomputes only what it affects, also an edit of a class, function or constant a script uses. A new baseline entry,ignoreErrors, the error format, options PHPStan reads only to report errors and the update of a package neither the scripts nor a type extension use rebuild nothing; loading a PHP extension (a profiler) changes the cached types only when a script uses one of its functions, classes or constants. - A cycle of plain includes is reported (
orisai.spaghetti.includeCycle) and its files are not followed; aninclude_once/require_onceof a file already included on the way there is a no-op whose value istrue. - A variable the included file
unset()s is undefined after the include, or possibly undefined when the file unsets it conditionally or maybe runs. - A PHPDoc at the top of an included file may declare its variables (
/** @var Foo $foo */). It is the file's contract, like the parameter types of a method: inside the file a declared variable has the declared type, and every include site has to pass a subtype. A mismatch is reported at the include statement, as PHPStan reports a wrong argument at a call:orisai.spaghetti.includedVariableType("Variable $count of included file header.php expects int, string given."),orisai.spaghetti.includedVariableUndefinedwhere the site does not define a declared variable,orisai.spaghetti.includedVariablePossiblyUndefinedwhere it may not define it. A variable the header does not declare is forwarded with the include sites' type. PHPStan checks the header itself (an unknown class in a tag); its check of the header against the native types of the forwarded variables (varTag.nativeType) is left out. - A variable an included file reads unguarded at its top level without declaring it (not in
isset(),empty()or the left side of??) and does not define itself before the read on any path is a requirement of the file, reported at each include site that does not define it: "Included file row.php reads $item, which is not defined here." (includedVariableUndefined; "… might not be defined here.",includedVariablePossiblyUndefined, where the site may not define it), with the line of the read in the tip. A file that passes the variable on to a file it includes requires it too, and the gap is reported at its own includers. PHPStan's own "Variable $item might not be defined." on that read inside the included file is left out, since the include sites are reported instead; in an entry point, an entry script and an included file no analysed file reaches it stays. A read of a variable the file defines itself on some paths only is the file's own "might not be defined", reported by PHPStan in the file, not at the include sites. - The header may declare optional inputs:
/** @var-optional bool $requiresLogin */(or@phpstan-var-optional). A site that does not define the variable is not reported; a site that does must pass the declared type. Inside the file the variable might not be defined: read it guarded or give it a default ($requiresLogin = $requiresLogin ?? true;,$requiresLogin ??= true;orif (!isset($requiresLogin)) { $requiresLogin = true; }); after such a default at the top level it has the declared type joined with the default's, in the file and for the includers. - The header binds the included file too, as PHPStan checks what a method assigns to a by-reference parameter
(
parameterByRef.type): an assignment at the file's top level giving a declared variable a type the header does not accept is reported there (orisai.spaghetti.headerVariableAssignType: "Variable $count declared by the file header expects int, string assigned."), since the include sites continue with what the file assigns. Every way of assigning counts (=,.=and the other operators, a write through an offset,foreach,catch, a destructuring); assigning a subtype (narrowing) andunset()are fine, assignments in functions, methods and closures the file declares are not checked, and amixedvalue is reported only withcheckExplicitMixed(orcheckImplicitMixed), as in PHPStan's rules;treatPhpDocTypesAsCertaindoes not change it, as it does not change PHPStan's rule. A file nobody includes is not checked: its header is a plain@var. - The header may also declare the file's outputs, after PHPStan's
@param-out:/** @phpstan-var-out Foo $foo */(or@var-out). At every point where the file goes back to the includer (eachreturnand each uncaughtthrowat the top level, and the end of the file; a path ending withexitor a never-returning call does not go back) a declared output must be defined with the declared type, as PHPStan types it there (afterassert(), an inline@varor a condition narrowed it):orisai.spaghetti.headerOutputUndefined,headerOutputPossiblyUndefined,headerOutputType. A wrong type is reported at the writes that give it ("Variable $title declared as output by the file header expects string, string|null given at the end of the file, written here."), or where the file goes back when no write explains it; amixedvalue only withcheckExplicitMixed(orcheckImplicitMixed). An output may be an input too, with another type: inside the file it starts with the@vartype. The includer continues with exactly the declared type. Once a file declares any output, its outputs are closed: a variable it defines, overwrites or unsets that the header does not declare and that the includer then reads is reported at the include (orisai.spaghetti.undeclaredIncludeOutput;possiblyUndeclaredIncludeOutputwhere the file writes it only on some paths or binds it by reference in a closure,function () use (&$total), which writes it only if called), bootstrap include or not. Passing a variable to a by-reference parameter counts as a write (sort($rows), a method's&$into), with the out type PHPStan resolves for the call (@param-out, also a conditional or generic one); it is certain only where the callee promises the write (a@param-out, an internal function's out type such aspreg_match()'s$matches, or a function PHPStan models such assort()), otherwise a by-reference argument "may" overwrite the variable. A tag that does not name a type and a variable is reported (orisai.spaghetti.headerOutputInvalid), and its type is checked as PHPStan checks a@vartype (class.notFound,varTag.unresolvableType); in a file nobody includes the tags do nothing.@var-outand@var-optionalare read only in the header: anywhere else they are reported and ignored (orisai.spaghetti.outputTagNotInHeader,optionalTagNotInHeader). - A header variable neither the file nor any file it includes at its top level, transitively, ever reads is reported
on its tag (
orisai.spaghetti.headerVariableUnused): the tag can be removed, and while it is there the include sites still have to pass the variable. Reading counts at the top level (also inisset(),empty(),??,compact('name'), a string, a closure'suseor an arrow function, or passed by reference) and in a function or method throughglobal $xor$GLOBALS['x']; only assigning,unset()ting or declaring a variable is not reading it, and a file included from a function does not see the top level. A file reading variables by name (extract(),$$name,get_defined_vars(),$GLOBALSat the top level,eval,call_user_func('extract', …), an include whose path is not resolved) reads every variable. - A variable an include defines that the including code then reads is reported at the include, unless the include is
a bootstrap include (
orisai.spaghetti.variableDefinedByInclude: "Variable $filename read after the include is defined only by included file payments_to_xls.php."), once per include and variable. It is a weaker finding, a hidden output rather than a bug: the variable was not defined before the include (not even on some paths), and the code after the include, or a file it includes later in the same scope, reads it before assigning it again. A bootstrap include is the first include of the including code (its file's top level, or a function's body) before which that code assigns only variables the included file reads ($requiresLogin = false; require 'init.php';); the optionbootstrapFilesreplaces this criterion with a list of files. - After an include the extension cannot follow (a path not discoverable, or naming no file), anything may be defined:
the certain "not defined" findings after it are reported in their weaker tier (
includedVariablePossiblyUndefined,headerOutputPossiblyUndefined); type findings stay.
Configuration
parameters: orisai: spaghetti: # Directory ./ and ../ paths are resolved from; null: the directory of the including file workingDirectory: null # include_path the scripts run with; null: ['.'] includePath: null # Processes walking the scripts when the types are computed; null: as many as PHPStan's parallel analysis # may use (parallel.maximumNumberOfProcesses; auto: the CPU cores, at most 20), 1: only the main process # (also without the pcntl and posix extensions, e.g. on Windows) workers: null # Files whose includes are bootstrap includes (relative to the working directory or absolute): a variable # they define and the includer reads is not reported; null: the first include of the including code, # where that code assigned only variables the included file reads before it bootstrapFiles: null # Files analysed as entry scripts (accessed directly, starting with no variables) even where something # includes them, in addition to the files nobody includes (relative to the working directory or absolute, # * and ? as in fnmatch()); null: none entryScripts: null
Assumptions
The analysis is only as good as these assumptions hold for your code:
- Closed scope. Every include of a file is visible to the analysis. An include whose path cannot be resolved breaks this, and is reported.
- An included file is never accessed directly. A file with at least one include site is analysed only with the
variables of its include sites; a file nobody includes is an entry point, starting with no variables. A file that is
both, included and accessed directly, is listed in
orisai.spaghetti.entryScripts: it is analysed as an entry point and still followed at its include sites. - A file with a single include site runs there, also through
include_onceorrequire_once. - The working directory and the include path are fixed. The working directory is the including file's directory
(a script requested directly runs in its own directory) unless
orisai.spaghetti.workingDirectorynames it; the include path is.unlessorisai.spaghetti.includePathlists it.chdir()andset_include_path()in the code are not followed.
Known limitations
- A variable which is possibly undefined at the top level of a script is
mixedin PHPStan, whatever its type at the include sites, and staysmixed(withoutnull) afterisset()or??. PHPStan treats any variable defined in only some branches at the top level this way. - The effects of an include used inside an expression (
if ((include 'x.php') === false)) are not applied, only its value; an include statement and an include assigned to a variable ($config = include 'config.php';) apply them. - A reference the included file creates (
$a = &$b;) gives both variables their types, but does not link them after the include. - An include reached through a called function is not followed from the caller: in
function load() { include 'config.php'; } load();the include runs inload()'s own scope, and the caller's variables,_oncestate andglobalvariables are not passed in or changed by it. - A helper that includes a path it is given and
extract()s variables into it is not followed, and its include is reported as not discoverable:function render($file, $vars) { extract($vars); include $file; }. - With orisai/phpstan-nette, the fields of a Nette form do not cross an include: an included file sees the form's class,
so
$form['email']there is any component and a missing name is not reported; the includer does not see the fields the included file adds; after an include of a file that may read or write the form variable (or of one the package cannot resolve), a name the form lacks is only possibly missing and its values are open. An include of a file that never touches the variable leaves the form as it was: the package tells orisai/phpstan-nette which locals each include may reach, from the include graph (a file outside the analysed paths reaches only the variables its header names).