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.
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-nette:1.x-dev phpstan/extension-installerNeither package has a release yet: the extension requires orisai/phpstan-nette 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.
phpstan/extension-installer includes the extension's configuration. The extension depends on orisai/phpstan-nette for now, which the installer would include too; without a Nette application, leave it out:
{
"extra": {
"phpstan/extension-installer": {
"ignore": ["orisai/phpstan-nette"]
}
}
}Without the installer, include the configuration yourself:
includes:
- vendor/orisai/phpstan-spaghetti/extension.neon- 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 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. - 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). On every path back to the includer (eachreturnat the top level and the end of the file; a path ending withexitdoes not return) a declared output must be defined with the declared type (orisai.spaghetti.headerOutputUndefined,headerOutputPossiblyUndefined,headerOutputType: "Variable $title declared as output by the file header expects string, string|null given at the end of the file."), and each assignment of it is checked against that type (headerOutputType). 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), 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). 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. - 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.
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: nullThe 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 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.
- 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).
