Skip to content

Latest commit

 

History

History
345 lines (221 loc) · 31.4 KB

README.md

File metadata and controls

345 lines (221 loc) · 31.4 KB

PHPStan

PHPStan is a static analysis tool for PHP that checks your code for errors without needing to execute the specific lines or write extra tests.

Running the tests

PHPStan requires PHP and Composer dependencies to be installed. Since there is no composer.lock, run composer update after pulling changes to composer.json, such as the addition of a PHPStan extension, or PHPStan will fail to load the configuration.

If you don't already have an environment ready, you can set one up by following these instructions.

Then you can launch the tests by running:

npm run typecheck:php

which will run PHPStan in the Docker container.

This runs two analyses, one after the other: the whole codebase with phpstan.neon.dist, and then the paths held to a stricter rule level with phpstan-strict.neon.dist, as described in Stricter analysis of selected paths. The command fails when either of them reports an error.

Additional flags supported by PHPStan can be passed by passing -- followed by the flags themselves. For example,

# to increase the memory limit from the default 2G to 4G:
npm run typecheck:php -- --memory-limit=4G

# to analyze only a specific file:
npm run typecheck:php -- src/wp-includes/template.php

# To scan with verbose debugging output:
npm run typecheck:php -- -vvv --debug

If you are not using the Docker environment, you can run PHPStan via Composer directly:

composer run phpstan

composer run phpstan -- --memory-limit=4G
composer run phpstan -- src/wp-includes/template.php
composer run phpstan -- -vvv --debug

Note the -- in each of those. Composer needs it in order to pass the flags on to PHPStan rather than reading them as its own, and without it they are discarded silently. The npm script supplies it, which is why only one is needed there.

The flags are passed to both analyses, except that paths, --configuration, --level, --error-format, --generate-baseline, and --fix-ignored run only the first, since each only makes sense for one. To run only one of them, as CI does, use composer phpstan:default or composer phpstan:strict. Those always use the .dist configurations, ignoring a local override.

For available flags, see https://phpstan.org/user-guide/command-line-usage.

Results on pull requests

Both analyses also run on every pull request that changes PHP files or the PHPStan configuration, as two jobs. The errors they report are shown in two places:

  • As annotations on the changed files. Most errors are annotated as warnings, which do not fail the check.
  • In a comment on the pull request, which lists every error in a table along with the commit it was first reported for. The comment is updated as new commits are pushed, moving each error that a commit resolves into a collapsed list of resolved errors, which also names that commit. Once all of the errors are resolved, the comment is marked as resolved and collapsed. The comment combines both analyses: an error reported by both is listed once, and when an error is only reported by the analysis of the strict paths, the table gains a Level column giving the rule level of each error.

Some errors cannot be ignored, and so cannot be reported as warnings either. These fail the check. The most common is an out-of-date baseline, which is reported when an error recorded in a baseline was fixed without the baseline being updated. Such an error is reported against a file rather than a line in it, so its annotation does not appear alongside the changes, and it would easily go unnoticed if the check passed.

The PHPStan configuration

The PHPStan configuration file is located at phpstan.neon.dist. It sets the standards the code is held to: the rule level, the baselines, the errors ignored as not actionable, and the strict rules enabled. It includes base.neon, which configures what PHPStan needs to know to analyze the codebase at all, such as the WordPress-specific extensions, the paths analyzed, and the supported PHP versions.

To override the default configuration, create a phpstan.neon file in the repository root, which PHPStan reads in place of phpstan.neon.dist. Include phpstan.neon.dist in it rather than copying it, so the override only states what it changes and keeps up with changes to the default configuration. For example, to analyze at a stricter rule level:

includes:
	- phpstan.neon.dist

parameters:
	level: 10

Strict rules

phpstan.neon.dist enables only the rules from phpstan-strict-rules which the code already complies with, registering each one individually. It does not include the package's rules.neon, since that file also makes several PHPStan parameters stricter, such as checkDynamicProperties and reportMaybesInMethodSignatures, even when its rules are disabled.

To work toward complying with more of them, include rules.neon in your phpstan.neon. It enables every rule and makes those parameters stricter, unless strictRules.allRules is set to false, in which case only the rules set to true are enabled but the parameters are still made stricter. Either way, disable the rules phpstan.neon.dist already registers, or each error they report is reported twice:

includes:
	- phpstan.neon.dist
	- vendor/phpstan/phpstan-strict-rules/rules.neon

parameters:
	strictRules:
		allRules: false
		disallowedLooseComparison: true
		overwriteVariablesWithLoop: true

		# Already registered in phpstan.neon.dist.
		disallowedBacktick: false
		disallowedShortTernary: false
		closureUsesThis: false
		matchingInheritedMethodNames: false

The rules for while and do-while conditions are only enabled with bleeding edge (as are those for unary + and - operands), so booleansInConditions: true alone does not cover loops. Set booleansInLoopConditions: true to enable them without it.

Seeing every error

The baselines and other ignored errors cannot be removed by leaving out an include, but a key ending in ! replaces the value it would otherwise be merged with. So to see every error, including those the baselines suppress:

includes:
	- phpstan.neon.dist

parameters:
	ignoreErrors!: []

Stricter analysis of selected paths

phpstan.neon.dist holds the whole codebase to a low rule level, since most of it does not yet meet a higher one. Some of it already does, mostly code added in recent releases, such as the AI client and the Abilities API. phpstan-strict.neon.dist holds those paths to a stricter rule level, currently 10, so that they keep meeting it. The level is set as a number rather than max, so that it is only raised deliberately, not by a PHPStan update adding a level.

phpstan-strict.neon.dist includes phpstan.neon.dist, so everything phpstan.neon.dist enforces still applies, and replaces the paths analyzed with the ones it lists under paths!. The rest of core is scanned instead, so that what those paths use is known. A scanned file gets the same WordPress-specific extensions as an analyzed one, because base.neon has every parse run them, so the types of the code outside the strict paths are the same as in the analysis of the whole codebase.

Errors are baselined in two layers. An error that the analysis of the whole codebase reports is baselined in baselines/, as usual, and stays baselined there for the strict analysis. What the stricter level adds in the strict paths is baselined in baselines-strict/, in the same way, and included through its own loader.php. composer phpstan:baselines and composer phpstan:fix maintain both.

To hold another path to the stricter level:

  1. Make sure no entry in baselines/ is for a file in the path. Both analyses enforce those entries, but each may report a different number of the errors one ignores, and then no count satisfies both. Fix those errors first.
  2. Add the path to paths! in phpstan-strict.neon.dist.
  3. Run composer phpstan:strict, and fix the errors it reports.
  4. Baseline any that cannot be fixed yet with composer phpstan:baselines.

In the strict paths, do not add an @phpstan-ignore comment for an error that only the stricter level reports. The analysis of the whole codebase does not report that error, so it reports the comment as ignoring nothing, and composer phpstan:fix would remove it. Fix the error, or baseline it instead.

A local phpstan-strict.neon overrides phpstan-strict.neon.dist, the same way phpstan.neon overrides phpstan.neon.dist. When a local phpstan.neon analyzes at the strict level or above, composer phpstan skips the second analysis, since it could only repeat part of the first. Only the levels are compared, so if the local phpstan.neon also narrows the paths analyzed, leaving out some of the strict paths, run composer phpstan:strict as well.

For more information about configuring PHPStan, see the PHPStan documentation's Config reference.

WordPress-specific extensions

This directory also contains extensions that teach PHPStan conventions specific to WordPress. They are registered in base.neon, so they apply to the default configuration and to any local override of it.

Global variables in function docblocks

Core documents the globals a function uses with @global Type $varname. GlobalDocBlockVisitor bridges that convention to PHPStan's variable type resolution, so those globals are typed rather than mixed inside the function.

Hash notation

Core documents the contents of an array or object with a nested list of @type tags, hash notation:

/**
 * @param array $args {
 *     Optional. An array of arguments.
 *
 *     @type string $post_type   Post type. Default 'post'.
 *     @type int    $post_author Post author ID.
 * }
 */

PHPStan reads that hash as free text, so the value stays a plain array and nothing inside it is typed. HashNotationVisitor translates it into the array or object shape PHPStan understands, which for the example above is array{post_type?: string, post_author?: int, ...}, so the same documentation serves the reader and the analysis rather than each shape having to be written a second time as a @phpstan-param.

A hash whose translation would be a guess is left alone, and the value keeps whatever type it has today. The visitor therefore only ever narrows a type, and never contradicts one:

  • A @phpstan-param or @phpstan-return written by hand always wins. Hash notation cannot express everything a type can — a function returning either of two shapes, or one whose return carries keys beyond those it documents, as get_avatar_data() returns the processed $args too — so a shape that has been tuned in the source is never overwritten by the derived one. Only the tag it was written for: a @phpstan-param for one parameter says nothing about the next, and a conditional @phpstan-return naming a parameter is not a shape for it.
  • The declared type has to name something a shape can be put on: a bare array or object, or a class, on its own or as one member of a union such as string|array or array|WP_Error — in a union the bare member is the one the hash is about, since a WP_Error carries no keys. A type that is already more specific than the hash, such as array<string, string|bool>, is left as written. The exception is a T[] whose hash is a single ...$0 entry typed as that T: the hash then describes the elements, as it does for the blocks parse_blocks() returns, so its array[] becomes array<array-key, array{blockName: string|null, attrs: array, innerBlocks: array[], innerHTML: string, innerContent: array}>, sealed like any other @return shape. An array[][] may document its outer elements as a bare array, as wp_print_font_faces() does, but only when their own hash goes on to describe the inner arrays the same way. A bare array beside the T[], as in array|array[], takes the shape instead. Named keys beside a T[] describe the array itself rather than its elements, so a string[] with named keys keeps its type.
  • The hash has to be well formed: every { closed by a } on a line of its own, and every @type carrying a $name and a type that PHPStan's own type parser reads as one. Asking the parser rather than describing what a type may contain is what keeps ?string, (string|null)[] and callable(): void from being turned away as malformed.
  • A hash on a bare object that would have to stay open is skipped, because PHPStan's object shapes have a fixed member list and no ..., and sealing one would report every member the hash does not name. A hash on a named class is kept: stdClass&object{...} is not sealed, since the intersection leaves the class to say what else may be read and a stdClass accepts anything. That is what lets the theme data WP_Theme_Install_List_Table::single_row() documents keep its shape while the wordpress.org API is still free to add to it.
  • A parameter taken by reference is skipped, because PHPStan checks a by-reference argument in both directions, and a shape there would be a contract every caller's variable has to satisfy before the call rather than a description of what the function reads.

Keys of a @param hash are optional, at every level, and the shape is left open with a trailing ..., because the hash lists the keys core reads rather than the only keys a caller may pass. Keys of a @return hash are required and the shape is sealed, since they describe a value core itself builds. Numbered keys such as $0 and $1 are required in either case, because positional arguments are passed in order. A description opening with Optional. overrides all of that, making the key optional. A Required. sentence, opening or closing the description, makes a @param key required, which is what a value such as a parsed block needs, since its keys are always set:

 * @param array[] $blocks {
 *     An array of blocks.
 *
 *     @type array ...$0 {
 *         @type string|null $blockName Required. Name of block.
 *         @type array       $attrs     Required. Attributes from block comment delimiters.
 *     }
 * }

Those two sentences are the only markers. Either word elsewhere in a description is prose, as in the "Optional self closing slash" of a match array whose every group is always set, or a "Capability required for the panel". Required. must also be capitalized, while Optional. may be written in any case: prose mistaken for Required. would report an error at every call that leaves the key out, whereas prose mistaken for Optional. only loosens the type.

Reading a key that a @return hash does not document is therefore reported rather than silently typed as mixed — unless the hash says otherwise itself, by listing a ...$N entry beside its named keys, which is how core writes "and the rest" for the positional hashes of wp_maybe_grant_site_health_caps() and WP_Meta_Query.

A hash on a class rather than on array or object produces an intersection, stdClass&object{...}, rather than a bare object shape. PHPStan's object shapes are structural, so a bare object{...} derived for a value core builds as a stdClass would no longer be assignable to a property declared stdClass. Intersecting keeps both: the value stays the class it is documented as, and its members are typed. This is why the returns that build one, such as get_taxonomy_labels(), document stdClass rather than object.

One kind of hash is outside what the visitor covers today: a @var hash on a property. A property declaration is inherited by every subclass and has to accept its own default, so a shape there would say more than the hash does — that no subclass may widen the property, and that the declared default already has the shape.

Hashes are also written on hook docblocks, where core documents apply_filters() and do_action(). Those are not attached to a function, but they are translated on the same terms, because the hook extensions below type a filtered value from the @param the hook documents. Without it a filter hands back a bare array — undoing, at the call, the shape the enclosing function's own hash established, as wp_set_cookie() does when it filters the $options its signature documents key by key. The same translation is applied where a docblock is inherited through a /** This filter is documented in <file> */ comment, so a hook is typed alike wherever it is fired.

Hook documentation

The remaining extensions read the docblock documenting a hook where the hook is fired, which is where WordPress documents its hooks. They cover apply_filters(), do_action() and their _deprecated and _ref_array variants.

  • The value a filter returns is typed from its documentation. apply_filters() returns the type of the first @param its docblock documents, rather than mixed. This assumes callbacks honor the documented type; one that returns something else is treated as the unusual case.
  • Hooks documented elsewhere are resolved. Core's /** This filter is documented in <file> */ convention is followed, in its action form as well, so a hook documented in another file is analyzed against its canonical docblock. A dynamic canonical name such as "{$type}_template_hierarchy" is matched against the literal name used at the referencing site.
  • Two rules check the documentation itself: that a hook is documented at all, and that it is fired with as many arguments as its documentation describes.

Calls whose hook name contains no literal text, such as the apply_filters_ref_array( $hook_name, $args ) re-dispatch in plugin.php, name no concrete hook and are skipped.

One consequence worth knowing: because a hook's documentation may live in a different file than the call inheriting it, editing a hook docblock in a file that reference comments point at discards PHPStan's result cache. Every call site inheriting that docblock has to be analyzed again, and PHPStan cannot infer that dependency on its own.

Errors these rules report

These identifiers are specific to WordPress, and can be ignored or baselined like any other error, as described below.

Identifier What it means
wordpress.hookDocMissing The hook is fired with neither a docblock documenting it nor a reference comment. Document it, or point at wherever it is documented.
wordpress.hookDocNoParams A filter's docblock documents no parameters. A filter always passes at least the value being filtered, so document that value with @param, plus one for each further argument. This also fires when an unrelated docblock, such as a @var annotation, happens to sit immediately above the call.
wordpress.hookDocReferenceFileMissing A reference comment names a file that does not exist in the tree being analyzed. The path is resolved relative to the file holding the comment and to the WordPress root; one that resolves outside the tree counts as missing, since the analysis does not read it.
wordpress.hookDocReferenceHookMissing The referenced file exists, but documents no hook of that name. Either the reference is stale, or the canonical docblock has moved.
wordpress.hookParamCountMismatch The call passes a different number of arguments than the docblock documents @param tags for. Passing fewer risks an ArgumentCountError in a callback registered for the documented count; passing more silently drops the extra argument and leaves the documentation misleading.

Ignoring and baselining errors

As we adopt PHPStan iteratively, you may be faced with false positives due to legacy code, or code that is not worth changing at this time.

PHPStan errors can be ignored in the following ways:

  • Using the @phpstan-ignore {error-identifier} (Reason for ignoring) annotation in the code itself. Avoid this if at all possible. An ignore comment stays in the code, hiding the error from every later analysis of that line, so first try to fix the error, or to correct the types that PHPStan relies on, such as those in a docblock. It is only for a false positive with a specific line of code that cannot be resolved any other way.

  • Adding the error pattern to the ignoreErrors section of the phpstan.neon.dist configuration file. This should be used to handle conflicts with WordPress Coding Standards or similar project decisions, or to allowlist legacy code that is not worth refactoring solely to satisfy the tests.

  • Adding an error to a "tech debt" baseline. This should be used for code that needs to be addressed eventually - by fixing, refactoring, or ignoring via one of the above methods - but is not worth addressing right now.

    Baselines are a useful triage tool for handling PHPStan errors in legacy code, as they allow us to enforce stricter code quality checks on new code, while gradually chipping away at the existing issues over time. Avoid adding PHPStan errors from new code whenever possible, and use baselines as a last resort.

How the baselines are organized

The baselines live in baselines/, one file per error identifier, such as variable.undefined.neon. Splitting them this way keeps each kind of error visible as a single file that should shrink to nothing and then be deleted, rather than as part of one large file in which every kind is mixed together.

phpstan.neon.dist does not list the baselines one by one. It includes baselines/loader.php, which includes every .neon file in that directory named for an error identifier, so a baseline takes effect as soon as it is added, and stops as soon as it is deleted, without an edit of the configuration.

Every entry is scoped to the file the error occurs in and carries an exact occurrence count:

-
	message: '#^Variable \$wpdb might not be defined\.$#'
	identifier: variable.undefined
	count: 4
	path: ../../../src/wp-trackback.php

Both the path and the count matter. A new occurrence of an already baselined error does not match the entry, even in a file that is already listed, and is reported as a new error. That is the point of recording them this way: the baselines describe exactly what exists today, so nothing new slips in behind them.

The consequence is that fixing a baselined error means updating its baseline as part of the same change, because the count no longer matches. A count that no longer matches is reported as an ignore.count error, and an entry that matches nothing at all as an ignore.unmatched error, neither of which PHPStan allows to be ignored or baselined. Either remove the stale entries with --fix, or regenerate the baselines.

Removing stale entries with --fix

PHPStan marks an error it can fix automatically with 🔧, and ends its report by saying how many there are. Stale ignores are among them: a baseline entry whose count is now too high, or that matches nothing at all, and an @phpstan-ignore comment that no longer ignores anything. Fix them in place with:

npm run typecheck:php:fix

or, outside the Docker environment:

composer phpstan:fix

This runs three steps:

  1. PHPStan with its --fix option, once with phpstan.neon.dist and once with phpstan-strict.neon.dist. It lowers the count of the entry, or removes the entry, leaving the rest of the baseline as it was. It is usually much faster than regenerating, since it reuses the result cache of the run that reported the errors. Unlike regenerating, it also removes an @phpstan-ignore comment that no longer matches. PHPStan says No fixable errors found for a configuration with nothing to fix, which does not stop the other steps.
  2. composer phpstan:baselines -- --prune, which deletes any baseline left with no entries. Removing the last entry of a baseline leaves the file behind, as ignoreErrors: []. Pruning analyzes nothing, so it can also be run on its own.
  3. Both analyses once more, which reuse the result cache and so are quick. PHPStan's --fix reports only what it fixed, and succeeds even when other errors remain, so this is what shows the errors that are left.

Keep in mind:

  • It always analyzes with the two .dist configurations, whatever a local phpstan.neon or phpstan-strict.neon says. A configuration at another rule level can report a baselined error with a different message, in which case --fix would remove an entry that the default configuration still needs.
  • It fixes every fixable error the run reports, not only stale ignores. A few other errors can also be fixed automatically, such as a useless cast, so check the diff before committing it.
  • PHPStan's --fix-ignored, run as composer phpstan -- --fix-ignored, goes further and also fixes the fixable errors which a baseline currently ignores. That is a way to work through a baseline, but expect larger diffs, and follow it with composer phpstan:baselines -- --prune.

The feature is marked experimental in PHPStan. See the PHPStan documentation for details.

Regenerating the baselines

The baselines are generated, and should not be edited by hand, other than by --fix as described above. Regenerate them with:

npm run typecheck:php:baselines

which will run the generator in the Docker container.

As with the analysis itself, flags are passed by adding -- followed by the flags themselves:

# a single identifier:
npm run typecheck:php:baselines -- --identifier=variable.undefined

# several, either comma separated or by repeating the option:
npm run typecheck:php:baselines -- --identifier=variable.undefined,isset.variable
npm run typecheck:php:baselines -- --identifier=isset.variable --identifier=empty.variable

# print every error as one baseline, writing nothing:
npm run typecheck:php:baselines -- --combined

# without analyzing anything, delete the baselines that list no entries:
npm run typecheck:php:baselines -- --prune

# the remaining options:
npm run typecheck:php:baselines -- --help

If you are not using the Docker environment, you can run the generator via Composer directly:

composer phpstan:baselines

composer phpstan:baselines -- --identifier=variable.undefined
composer phpstan:baselines -- --combined
composer phpstan:baselines -- --prune
composer phpstan:baselines -- --help

Note the -- in each of those. Composer needs it in order to pass the flags on to the script rather than reading them as its own, and without it they are discarded silently, so composer phpstan:baselines --identifier=variable.undefined regenerates every baseline rather than that one. The npm script supplies it, which is why only one is needed there.

A run also deletes any baseline whose identifier no longer reports anything. Since the baselines are included through baselines/loader.php, adding a newly split out baseline, and retiring one that has reached zero, need no edit of the configuration.

Each run regenerates both sets of baselines: those of phpstan.neon.dist in baselines/, and then those of phpstan-strict.neon.dist in baselines-strict/. The order matters, since the strict configuration includes the other one along with its baselines, so its own are only what is left over. The options apply to both, except --combined, which only prints the baseline of phpstan.neon.dist. To regenerate one set, name its configuration with --config, such as --config=phpstan-strict.neon.dist.

PHPStan's own --generate-baseline is deliberately not used directly. It captures every error a run reports, with no way to restrict it to one identifier, so it cannot refresh a single baseline without sweeping every other kind of error into it.

Performance and troubleshooting

PHPStan can be resource-intensive, especially on large codebases like WordPress. If you encounter memory limit issues, you can increase the memory limit by passing the --memory-limit flag as shown above.

PHPStan caches analysis results to speed up subsequent runs. You can see information about the results cache by running analyse with the -vv or -vvv flag.

Clear the cache after changing anything in this directory

The .cache directory holds more than the results. PHPStan also stores what it read out of each source file there, the docblocks and signatures it found, keyed by that file's contents and nothing else. The sources in this directory change what reading a file yields without changing the file: HashNotationVisitor rewrites a docblock in the syntax tree, and the bytes on disk stay as they were.

A cache written before one of them changed therefore answers with what the old code saw. The run does not fail or warn; it reports against types that are no longer derived, so a visitor can look as though it does nothing, or as though it does less than it does. So clear the cache by hand after editing anything here:

rm -rf .cache

The results cache alone is not the problem. PHPStan invalidates that itself when the configuration changes, and also when a bootstrap file or the source of any extension the configuration registers is edited, which covers every file in this directory that runs during analysis. What survives either is the per-file reflection, which is keyed by the source file's own contents and has no way to know that reading it now yields something else. CI keys its cache on these files for the same reason; see .github/workflows/reusable-phpstan-static-analysis-v2.yml.

Analyzing a subset of the tree used to call for the same treatment, the same silence arriving from the other direction. A file named on the command line is analyzed, but a file merely read on its behalf went to PHPStan's simple parser, where these visitors do not run, so the reflection stored for it carried no derived shape — wrong for that run, and there in the cache for the next full run to restore. base.neon now has the simple parser wrap the rich one, so every parse rewrites the same docblocks and a run over a subset derives what a full run derives. It does so by redefining one of PHPStan's own parser services, which is not a documented extension point; if a hash notation type ever looks wrong after a PHPStan upgrade, check that definition first.

Baseline generation is exempt from that last hazard. generate-baselines.php points its analysis at .cache/baselines instead, a directory only it writes to and only ever from a full run, so a baseline can never record a message derived from reflection some earlier narrowed run left behind. Clearing the cache after editing anything in this directory still applies to it, and the rm -rf .cache above covers both.

Sometimes, due to the lack of type information in legacy code, PHPStan may still struggle to analyze certain parts of the codebase. In such cases, you can use the --debug flag to disable caching and see which files are causing issues.