Repository navigation
Tools: Add PHPStan static analysis at rule level 5 - #66693
Merged
Merged
Conversation
|
👋 Thanks for your first Pull Request and for helping build the future of Gutenberg and WordPress, @justlevine! In case you missed it, we'd love to have you join us in our Slack community. If you want to learn more about WordPress development in general, check out the Core Handbook full of helpful information. |
justlevine
commented
Nov 2, 2024
This was referenced Nov 2, 2024
Closed
justlevine
force-pushed
the
tools/phpstan
branch
from
December 28, 2024 14:35
bd2e9c6 to
916c228
Compare
This was referenced Dec 30, 2024
Merged
Merged
This was referenced Nov 1, 2026
This was referenced Nov 1, 2026
This was referenced Nov 1, 2026
This was referenced Nov 1, 2026
Member
Member
There was a problem hiding this comment.
@manzoorwanijk I've opened #86222 to implement this.
Vedant-Gandhi
pushed a commit
to Vedant-Gandhi/gutenberg
that referenced
this pull request
Nov 30, 2026
* tools: Add and configure PHPStan static analysis
* Upgrade to PHPStan 2 and phpstan-wordpress 2
Require PHPStan 2.1 or newer and phpstan-wordpress 2.0 or newer, which
brings in the matching WordPress stubs. Rename the Composer script from
`analyse` to `phpstan`, as in WordPress core, and give it the same
memory limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Scan the built PHP files for the generated functions
The `gutenberg_*` functions and `*_Gutenberg` classes that `lib/` calls
are generated into `build/` by the build, so scan that directory. This
lets the ignore rule for unknown `gutenberg_*` functions go, and
`packages/` no longer needs to be scanned.
Also bring the paths up to date: `post-content.php` no longer exists, the
`html-api` compat directories were removed when the minimum WordPress
version went to 6.7, and executing `gutenberg.php` at bootstrap is not
needed for discovery. In the bootstrap, `SITECOOKIEPATH` and
`WP_TEMPLATE_PART_AREA_UNCATEGORIZED` are no longer referenced, while
`MEDIA_TRASH` now is; it is listed as a dynamic constant so that its
placeholder value is not treated as certain.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Analyze at rule level 5 with a single baseline
Start at rule level 5, as WordPress core does, and replace the per-level
PHP baselines for levels 0 through 8 with a single standard
`tools/phpstan/baseline.neon`, generated with PHPStan's
`--generate-baseline`. Report unmatched ignored errors, so baseline
entries are removed as the errors they cover are fixed.
Drop the ignore rule for unknown `gutenberg_*` functions, which the
scanned build files now resolve, and the level 6 ignore rule for the
WPCS iterable syntax. Leave `treatPhpDocTypesAsCertain` at its default,
as core does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Match WordPress core's PHPStan analysis settings
Set `phpVersion` to the supported range of PHP 7.4 through 8.5, so the
results do not depend on the PHP version PHPStan runs on, and store the
result cache in `.cache/phpstan` so CI can reuse it.
Also set `treatPhpDocTypesAsCertain` to false, as core's
`tests/phpstan/base.neon` does. This corrects the earlier commit that
claimed core leaves it at its default. PHPDoc types are not enforced by
PHP, so callers can pass values that do not match them.
With PHPDoc types no longer treated as certain, PHPStan can no longer
prove the always-false conditions in `gutenberg_tinycolor_bound01()` and
`gutenberg_tinycolor_hsl_to_rgb()`, and the ignore comments for them
became unmatched errors. They are turned into plain comments, which keep
the explanation of why the conditions never hold. The baseline is
regenerated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Run PHPStan in the unit test workflow
Add a PHP static analysis job alongside the PHPCS job. It reuses the
`build-assets` artifact that the PHP unit test jobs already download,
since the build generates the PHP files defining the `gutenberg_*`
functions and `*_Gutenberg` classes that PHPStan scans, so the build does
not run twice. Errors are reported as annotations on the pull request.
The result cache is restored from the latest run for the same week,
configuration, and dependencies, and each run saves its own. The job is
added to the status check's `needs`, so its result counts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Document running PHPStan in the coding guidelines
Explain how to run the analysis locally, why the build has to run first,
how to regenerate the baseline when a change fixes a baselined error, and
how to override the configuration with an ignored `phpstan.neon`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Declare the PHP polyfills that WordPress provides
With `phpVersion` starting at PHP 7.4, PHPStan reported the newer PHP
functions that WordPress polyfills in `wp-includes/compat.php`, such as
`str_contains()` and `array_is_list()`, as not found. The WordPress stubs
omit them, since they are defined conditionally, and core avoids the
problem only because it analyzes `compat.php` itself. That added 95 false
`function.notFound` errors to the baseline.
Declare them in a scanned `tools/phpstan/polyfills.php`, with the
signatures of the native functions. Only the polyfills available in the
minimum supported WordPress version, 7.0, are declared, so relying on one
added in 7.1, such as `clamp()`, is still reported.
With `array_is_list()` known, PHPStan now also reports a redundant
`array() !== $current` check in `Gutenberg_View_Config_Data`, which core
already dropped in its copy. It is left in the regenerated baseline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Analyze all the PHP that WordPress core ships from Gutenberg
Core copies the PHP in `block-library`, the widget blocks, `core-fields`,
and `core-actions` verbatim, and ships the PHP generated from the
`wp-build` templates, but excludes these copies from its own PHPStan
analysis because they are generated. The style engine and the default
block parser are synced into core as well. None of this was analyzed
anywhere, so analyze it here, where it is maintained.
The `wp-build` templates are not valid PHP, so the generated files in
`build/` are analyzed instead. The `node_modules` directories are
excluded from analysis and scanning, as in core, since the parser
package's dependencies include PHP.
The baseline is regenerated, now with 251 errors, of which 166 are in
the newly analyzed code: 145 in `block-library`, 16 from one line of
the page template, four in the style engine, and one in `core-actions`.
The docs say what the analysis covers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Analyze the wp-build PHP templates themselves
The PHP files that the build generates from the wp-build templates were
analyzed in `build/`, so problems in the templates were found, but they
were reported against the generated files: once for each page generated
from the page template, and never on the template line to change.
Analyze the templates instead. They are not valid PHP until the build
replaces their `{{PLACEHOLDER}}` tokens, so `WpBuildTemplateParser`
wraps the parser that PHPStan uses for analyzed files and substitutes a
representative value for each token first, modeled on what the build
generates. No substitution spans more than one line, so every reported
error, including a syntax error, points at the template line itself,
locally and in the annotations in CI. An unknown placeholder is reported
as such, rather than as a syntax error.
The templates are listed one by one, from a PHP config include that
globs them, rather than as their directory. PHPStan finds the functions
declared in an analyzed directory by reading the raw files, which fails
on a template, whereas it finds those in an analyzed file by parsing it.
The class is autoloaded from `tools/phpstan/src`. The regenerated
baseline has 237 errors, with the 16 for the empty script source in the
generated pages now two, one for each page template.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Correct the version comment on the composer-install pins
The pinned commit of `ramsey/composer-install` is its `4.0.0` tag; the
action has no `v4.0.0` tag, so zizmor reports the comment as not matching
the pin. Correct it for all three jobs that use the action, as core's
workflows already write it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Ignore Zizmor's cache poisoning finding for the unit test workflow
Zizmor treats a workflow that runs on pushes to `release/*` branches as
one that publishes release artifacts, and reports every cache its jobs
restore as open to cache poisoning: an attacker who could write a cache
entry on trunk could have it restored into the release build. Without
that trigger, the same workflow has no findings, which is also why
core's workflows, which cache in the same way, have none.
Nothing built in this workflow is published, though. Its jobs only
report test and lint results, and the `build-assets` artifact is only
used by its own jobs. So ignore the finding, with a single comment on
the `push` trigger that causes it, which covers the new PHPStan job's
two caches as well as the three that the PHP test and PHPCS jobs
already had. The comment above it explains the reasoning, and that the
ignore should go if the workflow ever publishes what it builds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use a native property type and only PHPStan's public API in the template parser
Declare the wrapped parser property with a native `Parser` type, since
PHPStan requires PHP 7.4 or newer.
The parser also constructed `ParserErrorsException` and called its
`getErrors()`, neither of which is covered by PHPStan's backward
compatibility promise, so a minor PHPStan release could break them.
Neither is needed:
* A syntax error in a rendered template already gets reported against
the template being analyzed, so it no longer has to be rethrown with
the file name.
* An unreadable template is handed to the wrapped parser, which reports
it as it does for any other file.
* A placeholder without a substitute is a gap in the parser rather than
an error in the template, so it now throws a `LogicException` naming
the placeholder, its line, and the template, which fails the run.
The parser now has no errors at rule level 10.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Address PhpStorm's inspections in the PHPStan tooling
* Rename the polyfill declarations to `polyfills.stub`, the extension
PHPStan uses for files that only declare signatures. Their empty
bodies are what a stub is, but as a `.php` file PhpStorm analyzed them
as code and reported each one as missing a `return` statement.
* In the template parser, import `LogicException` and the `Stmt` node
class rather than qualifying them, drop the redundant escapes of the
closing braces in the placeholder pattern, and name the `parseString()`
parameter `$sourceCode` as the interface does, so that it can be
passed as a named argument.
* Declare the bootstrap constants with `const` rather than `define()`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Add a phpstan:baselines Composer script, as in core
Regenerating the baseline meant spelling out
`composer phpstan -- --generate-baseline=tools/phpstan/baseline.neon`.
Add a `phpstan:baselines` script for it, named as in WordPress core so the
same command works in both. Core's script runs a wrapper that splits its
baselines by error identifier; Gutenberg keeps a single baseline, so its
script only passes PHPStan's own `--generate-baseline` the file to write.
It also passes `--allow-empty-baseline`, so the baseline can still be
regenerated once its last error is fixed.
The configuration comment and the coding guidelines now name the script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Add typecheck:php npm scripts that run PHPStan in wp-env
Add `typecheck:php` and `typecheck:php:baselines`, named as in WordPress
core, which run the `phpstan` and `phpstan:baselines` Composer scripts.
Core runs them in its own Docker environment; here they run in the
`wp-env` CLI container, as `lint:php` does for PHPCS, so contributors
without a local PHP can run the analysis. Arguments after `--` are
passed on to PHPStan.
The bare `typecheck` script stays the TypeScript check, the way `lint`
does not include `lint:php`: it runs in CI and in the editor workflow
without the local environment, which these need.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* List the PHPStan errors in the job summary
An annotation is only shown alongside the changes in a pull request when
its line is part of the diff, and GitHub shows at most ten error
annotations per step. An error on a line the pull request did not
change, or one with no line at all, was otherwise only in the log, with
nothing but a failed check to show for it.
PHPStan now writes a JSON report, which `phpstan-report.js` turns into the
annotations, and into a job summary listing every error with a link to
its line. An out-of-date baseline, the most common error away from the
changed lines, gets its own explanation there: it is expected after a
pull request fixes a baselined error, and the fix is to regenerate the
baseline with `composer phpstan:baselines`, rather than to change the
code. The job still fails on any error.
This follows the report that core's PHPStan workflow writes, but keeps
the errors as errors rather than warnings, since Gutenberg merges on
GitHub and relies on its checks to keep new errors out.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Let a local PHPStan configuration opt in to analyzing the tests
The tests in `phpunit/` are not analyzed by default, since they do not
ship in core, but a local `phpstan.neon` can now add them to the paths:
* Require `phpstan/phpstan-phpunit`, the PHPUnit extension core uses,
which the extension installer enables. It only acts on test code, so
the regular analysis is unaffected.
* Require `php-stubs/wordpress-tests-stubs` and scan it, for the
WordPress test library that wp-env only provides at runtime, such as
`WP_UnitTestCase` and its factories. Without it, analyzing the tests
reports 4,832 errors, nearly all for those unknown classes; with it,
287.
* Define the constants the test bootstrap provides, `DIR_TESTDATA` and
`WP_TESTS_DOMAIN`, and `WP_TEMPLATE_PART_AREA_UNCATEGORIZED`, which the
WordPress stubs lack.
The last of those also resolves two `constant.notFound` errors in the
template part block, so they are removed from the baseline. The coding
guidelines show the configuration that opts in to the tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Always generate the baseline from phpstan.neon.dist
PHPStan uses `phpstan.neon` in place of `phpstan.neon.dist` when it
exists, so with a local configuration, such as one that raises the rule
level or adds the tests, `composer phpstan:baselines` would have written
that configuration's errors into the committed baseline. Pass
`phpstan.neon.dist` explicitly, as core's baseline generator does, so the
baseline only ever records what CI analyzes. The `typecheck:php:baselines`
npm script runs the same Composer script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Explain why the PHPStan report script prints the annotations
The annotations were printed by PHPStan itself before, with its `github`
error format. Say in the script's docblock that it now prints them because
PHPStan writes JSON for the job summary, and can only produce one format
per run. Also correct the claim that errors away from the changed lines
were otherwise only in the log: they are listed with the run's
annotations, unless they fall past the tenth.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Revert an accidental change to gutenberg.php
The previous commit swept in a throwaway test change that was staged at
the time, renaming the `plugin_basename()` call to a function that does
not exist. Restore the line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Pin the PHPStan packages to exact versions
There is no lock file, so a caret range installs whatever was released
last. A new PHPStan release, or new WordPress stubs, can report new
errors or stop reporting baselined ones, and with
`reportUnmatchedIgnoredErrors` either fails CI on every pull request at
once. Pin the versions the baseline was generated with, as core does, so
an upgrade is a deliberate change that regenerates the baseline.
The WordPress stubs were only required through the WordPress extension,
so require them directly to pin them as well. The extension installer
stays a range, since it does not affect the results.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Only advise regenerating the baseline when an error was fixed
PHPStan reports `ignore.count` both when a baselined error occurs fewer
times than recorded and when it occurs more times. The job summary
treated both as a stale baseline and advised regenerating it, which in
the second case would record a newly added occurrence as accepted.
Tell the two apart by PHPStan's message, which says "occurred only" when
there are fewer. Keep the advice to regenerate for that case, and for the
other say that the pull request likely added an occurrence to fix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Leave the baseline out of the PHPStan cache key
The key hashed every file in `tools/phpstan`, including the baseline, so
each pull request that fixed a baselined error started from an empty
cache and saved a cache of its own under a new key. The baseline only
filters the reported errors, so leave it out, as core does.
The `tools/phpstan/*` pattern also did not match the parser in
`tools/phpstan/src`, which does change the analysis, so hash that too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Report a PHPStan run that wrote no report
PHPStan also exits with 1 when it cannot load the configuration, and
then writes the reason to stderr and nothing to the report. The run step
lets that status through as a run with errors, and the report script then
failed on `JSON.parse` with a Node stack trace that did not say what went
wrong.
Say instead, as an annotation and in the job summary, that PHPStan did
not complete, and point to the run step's output for the reason.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* List at most 500 PHPStan errors in the job summary
GitHub drops a job summary larger than 1 MiB entirely, so a run with
thousands of errors, such as after a PHPStan upgrade, would have shown
none of them there. List the first 500 and say how many more are in the
step's output, where every error is still printed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Locate PHPStan errors in traits by the trait's file
PHPStan keys an error in a trait by the trait's file followed by
" (in context of class Foo)", for the class it was analyzed in. Passed
through as the path, the annotation did not attach to the file and the
link in the job summary led to a page that does not exist. Strip the
suffix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Discover the functions the wp-build templates declare
PHPStan finds the symbols a file declares by parsing it with its simple
parser, not the rich parser used for the analysis, and only the rich
parser was replaced to render the templates. Parsing a raw template
failed, so none of its functions were found. The analysis still passed
because the templates were rendered with the `gutenberg` prefix, and the
scanned files in `build` declare functions by the same names. A call in
a template was therefore checked against the built function, which can
be out of date with the template.
Replace the simple parser as well, and render the templates with a
prefix that no built file uses, so that a template's calls resolve to
the template's own functions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Pin the PHPStan extension installer too
It was left as a range since it only includes the configuration of the
extensions that are installed, which are pinned. A new release could
still change how it does that, though, and it costs nothing to pin, so
every package that affects the analysis is now at an exact version.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Analyze against the WordPress 7.0 stubs
The plugin supports WordPress 7.0, but the stubs were those of 7.1, which
declare the functions, classes, and methods added in 7.1. A call to one
of them without a guard would pass the analysis, and then be a fatal
error on 7.0. This also contradicts the polyfill stubs, which leave out
the 7.1 polyfills for this very reason.
Pin the stubs to 7.0.1, the latest release for 7.0, and regenerate the
baseline. Nothing it newly reports fails on 7.0:
* The calls to `register()` and `unregister()` on the result of
`WP_Icons_Registry::get_instance()` reach the Gutenberg subclass, which
replaces the shared instance when it loads, and in which both are
public.
* The call to `WP_Theme_JSON::get_viewport_media_queries()` in the
Navigation block is guarded by `method_exists()`.
* The rest are argument types that the 7.0 stubs declare differently.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* List PHPStan errors that belong to no file first
The errors that are not specific to a file, such as an internal error or
a configuration problem, were added after all the others, so the limits
of 10 annotations and 500 summary rows dropped them first. They are
about the run itself, and the hardest to find in the log, so put them
first instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Only advise regenerating the baseline when nothing else is reported
When a pull request changes a line with a baselined error, the error can
come back with a different message, so that its baseline entry no longer
matches and the error is reported as a new one. The job summary then
said that the baseline was out of date and should be regenerated, which
would record the new error as accepted.
When the run reports other errors alongside out-of-date entries, say to
fix those first, and only then regenerate the baseline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Only save the PHPStan result cache on trunk
Every run saved a cache of its own. One saved for a pull request can only
be restored by that pull request, though, so with the number of pull
requests this repository gets, these would mostly use up its cache
storage and push out the caches that every run restores, such as those
for npm and Composer.
Restore the cache in every run, and save it only on pushes to trunk, so
that pull requests start from the latest cache of trunk.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Point from wp-build's template replacements to the PHPStan parser
The parser that renders the templates for PHPStan substitutes a sample
value for each placeholder, modeled on what the build generates. A
placeholder it does not know fails the analysis, but if what a known
placeholder expands to changes shape, the parser goes on analyzing the
old one without notice. Say where the sample values are, next to the
function that applies the real ones.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Analyze against stubs generated from WordPress core trunk
Gutenberg tracks core trunk, so the stubs released for a WordPress
version lack what trunk has added since, and the analysis would report
code that uses it. The 7.0 stubs it used instead report a call to a
trunk function as not found, and miss core's newer types.
Until php-stubs/wordpress-stubs publishes stubs built from trunk,
generate them with its generator from a pinned trunk commit, r64757,
which no longer has the global type aliases that the stubs could not
carry. The generator is pinned to the head of its PR 498, without which
it adds a second `@phpstan-return` to the docblocks that now have their
own in core.
The stubs are committed in tools/phpstan/wordpress-stubs/ as a path
package named php-stubs/wordpress-stubs, in place of the released one,
since szepeviktor/phpstan-wordpress loads them from that package's path.
The stubs have the .stub extension and are marked as generated in
.gitattributes, with a small PHP file at the expected path to load them.
They are also part of the CI cache key for the PHPStan result cache.
Regenerate the baseline, from which 18 entries go, while 2 calls that
only WordPress 7.0 or 7.1 need are now reported.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Explain the block passed to wp_get_elements_class_name()
Since WordPress 7.1 the function takes no parameters, and the trunk
stubs report the block passed to it. WordPress 7.0, which the plugin
still supports, requires the block, while 7.1 ignores it. Keep the
argument, and ignore the error inline with that reason in place of its
baseline entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Explain the guard for core's reaction summary pre-fetching
The trunk stubs declare WP_REST_Comments_Controller's
prefetch_reaction_summaries(), so the method_exists() guard that skips
Gutenberg's own pre-fetching is reported as always true. The method
does not exist before WordPress 7.2, so keep the guard, and ignore the
error inline with that reason in place of its baseline entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Declare the clamp() polyfill from WordPress 7.1
The polyfill stubs left out those added in WordPress 7.1, so that the
analysis matched the minimum supported version. Now that the WordPress
stubs follow core trunk, the polyfills follow it too.
Of the three that were omitted, only `clamp()` needs declaring, since
PHPStan already knows `mb_chr()` and `mb_ord()` as mbstring functions.
Also correct why the stubs omit compat.php: a polyfill there would
redeclare a native function when the stubs are executed as a bootstrap
file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Mark the PHPStan stub files as PHP
Linguist does not recognize the .stub extension, so GitHub shows the
polyfill stubs and the generated WordPress stubs as plain text. Set
their language to PHP, and use Git's PHP diff driver so that the hunk
headers name the enclosing function.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Add a wp-build changelog entry for the template replacement note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Run the WordPress stubs generator as a Composer script
The generator could only be found by looking in tools/phpstan. Expose
it as `composer phpstan:generate-wordpress-stubs`, next to the other
PHPStan scripts, and describe in the coding guidelines how to update
the stubs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Note the SVN revision and version of the pinned core commit
A bare commit hash says nothing about how recent the stubs are. Follow
it with the SVN revision and the $wp_version at that commit, the way a
pinned GitHub action is followed by its version.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Say that generating the WordPress stubs is temporary
Once php-stubs/wordpress-stubs publishes builds from core trunk, a
pinned one can be required like any other dependency. Say so in the
generator, along with what to remove then.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Generate the WordPress stubs from trunk, a core PR, or a checkout
A Gutenberg change often depends on a wordpress-develop pull request
that adds what it uses, and with the stubs pinned to a trunk commit in
the script, the analysis reported those uses until the core change was
committed and the pin bumped by hand.
The generator now takes the source as an option: `--commit=<ref>`, such
as `trunk`, `--pr=<number>` for the head of a core pull request, or
`--checkout[=<path>]` for the working tree of a wordpress-develop
checkout, by default the one Gutenberg is in, with any uncommitted
changes to tracked files. A commit is read from that checkout when it
has it, and is fetched from GitHub otherwise.
The commit is no longer hard-coded in the script. The package's
composer.json records the source, so that running the generator with no
option reproduces the stubs, and the stub header says where they came
from: the trunk commit and its revision, or the pull request and the
trunk revision it is based on. Stubs generated from a pull request are
meant to be committed with the change that depends on it, and
regenerated from trunk once the core change is committed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Cache the stubs generator, and allow overriding its source
Each run fetched the generator and installed its dependencies again.
Keep it set up in .cache/wordpress-stubs-generator, by repository and
commit, and generate in a copy, so that the cached one stays unchanged.
With the wordpress-develop commit in the enclosing checkout too, a run
then needs no network at all.
The generator's repository and commit, the wordpress-develop
repository, and the cache directory can now be overridden with
environment variables, such as to try a generator change. The stub
header names the generator repository that was used.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Generate the WordPress stubs on demand instead of committing them
The stubs are a 6 MB generated file, which every pull request that
updates them carries as a diff. The package's composer.json already
records the core commit or pull request they are generated from, so
commit only that, and ignore the stubs.
Run with no option, the generator now does nothing when the stubs were
generated from that source, and generates them otherwise. The stubs
record a key for the source, the generator, and the script itself, so a
pull that changes any of them generates them again. Only the options
write the recorded source, so a regeneration leaves composer.json as it
is. Stubs generated from uncommitted changes in a checkout are used as
they are, since they cannot be generated again.
`composer phpstan` runs the generator first, which reports on standard
error so that a report read from standard output stays intact. The path
repository is now required to be a symlink, since the stubs are
generated next to the package's composer.json, and the bootstrap file
explains how to generate them when they are missing, such as when
PHPStan is run directly.
CI caches the stubs by the recorded source and the script, so it only
generates them when either changes, which took 24 seconds from scratch
locally.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Install the stubs generator from a committed lock file
Now that CI generates the stubs, a cache miss would install whatever
versions of the generator's dependencies are current, such as of
php-stubs/generator, nikic/php-parser, and
phpdocumentor/reflection-docblock, which determine its output. A new
release could then change the stubs and break the baselines without any
commit changing. The generator does not commit a lock file, so commit
one here, and install from it.
When the lock file is missing, such as after changing the generator's
commit, the dependencies are updated and the lock file is written for
committing. The cached generator and the generation key include the lock
file, so a change to it generates the stubs again, as does the CI cache
key.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Pin the stubs generator's output packages instead of locking them
Gutenberg has no Composer lock file. It pins its development tools that
affect the results to exact versions in composer.json, such as PHPStan,
and lets their dependencies float. Do the same for the generator in
place of the 148 KB lock file: require exact versions of the packages
that determine its output, php-stubs/generator, nikic/php-parser,
phpdocumentor/reflection-docblock, phpdocumentor/type-resolver, and
phpstan/phpdoc-parser, before resolving the rest. Its other dependencies
are its own development tools, such as PHPUnit and PHPCS.
The pinned versions are those that the lock file had, and the stubs are
unchanged. They can be overridden with an environment variable, like
the generator's commit, and are part of the cached generator's directory
and of the generation key.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Port the WordPress stubs generator from bash to PHP
Now that `composer phpstan` generates the stubs first, every analysis
depends on the generator script. Composer runs scripts through cmd.exe
on Windows, which cannot run a bash script, so the analysis no longer
ran there, while it did when the stubs were committed. The generator's
own generate.sh is bash too.
The script is now PHP, which Composer always has, and runs Git and
Composer without a shell, passing arguments as arrays, so that nothing
needs quoting on any platform. It does what generate.sh does for trunk
itself: it fixes the `binary string` type in the AVIF class, runs
generate-stubs with the generator's finder and visitor, and appends the
`$wpdb` shim. Its Requests 1.x step only applies to versions of
WordPress that bundle that library, which are now rejected. Since the
generator reads the WordPress source from its working directory, it
runs in the work directory against the cached generator, which no
longer needs copying.
A commit in the enclosing checkout is checked out with an index of its
own, rather than with `git archive` and `tar`, and the generator is set
up inside the cache directory before being moved into place, so that
the move never crosses file systems.
The stubs are byte-identical to those of the bash script, apart from
the script's name and the generation key in the header, for a trunk
commit read locally and fetched with a cold cache, and the `--pr` and
`--checkout` modes behave as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Address PhpStorm's inspections of the stubs generator
- Match the usage block by its line breaks, rather than with `^` inside
the pattern, which PhpStorm flags as an anchor in an unexpected
position.
- Interpolate array elements without braces where none are needed.
- Name the temporary directories with `uniqid()` in place of
`random_bytes()`, which can throw. The names only need to be unique,
and `mkdir()` fails when one is not. Document that
`create_directory()` throws then.
- Have `read_recorded()` return the recorded commit, pull request, and
whether the changes were uncommitted as a typed shape, checking each
value's type in one place rather than in `main()`.
PHPStan at level 9 and PHPCS report nothing for the file either.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Address PhpStorm's grammar and spelling checks in the stubs generator
- Use "afterward", the American English form.
- Format the `source/wordpress` path as code, so that it does not read
as a misspelling of WordPress.
- Register the cleanup of the temporary directories as closures, rather
than as the string `__NAMESPACE__ . '\remove_path'`, in which the
spell checker reads `\r` as an escape, leaving "emove". A closure also
makes the call checkable by static analysis.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Reword the stubs generator's comments without the source path
PhpStorm's grammar check still flags `source/wordpress` as a misspelling
of WordPress when formatted as code, so describe what the path is for
rather than naming it. The code beside the first comment names it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Narrow the stubs generator's PHPDoc types
Declare what each function relies on: non-empty strings for paths,
repositories, commits, and settings, which fall back to their defaults
when empty; non-empty lists for commands and sparse checkout patterns;
the three output modes of `execute()` as literal strings; a positive
revision; and a numeric pull request number in the recorded source.
`usage()` is declared to never return, so that the analysis knows the
values it guards.
The checks that this needs are real ones:
- A new `resolve_commit()` verifies that a ref names a commit and
returns its hash, for HEAD of the checkout and of the fetched clone.
- A commit that is still empty after the options are resolved is
rejected before anything is fetched.
- A checkout whose path does not resolve is rejected, rather than cast
to an empty string.
- A revision or pull request number of 0 is not accepted.
The revision lookup, which was repeated for the checkout and the clone,
now follows them once. PHPStan at its maximum level, PHPCS, and
PhpStorm report nothing, and generating from a trunk commit, locally
and with a cold cache, from a pull request, and from a checkout with
uncommitted changes, behaves as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Realign the parameter columns in the stubs generator's docblocks
The narrowed types of `execute()` and `run()` left their variable names
and descriptions out of line with the longest type.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Replace compound ternaries with early returns in the stubs generator
`composer()` and `setting()` each returned a ternary whose condition
was two comparisons, which made the line hard to read. Return the
fallback early instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Improve docblock formatting
* Indent the stubs header heredoc
With the flexible heredoc syntax of PHP 7.3, which the plugin's minimum
of 7.4 allows, the header's body and closing marker can be indented. Do
so by one level more than the surrounding code, so that the header text
stands apart from it. The closing marker's indentation is removed from
each line, so the generated header is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Note what to do once core's AVIF info types are fixed
Once the PHPDoc types in core's AVIF info class are corrected, the
generator no longer needs to rewrite them, and the recorded commit
should be bumped to one that includes the fix. Mark the rewrite as
removable then, and add a TODO beside the recorded commit. JSON has no
comments, so it goes under `extra`, which the generator does not read
beyond `extra.source`. Regenerating the package drops it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Generate the WordPress stubs from r65047
Bump the recorded core commit to r65047, which corrects the PHPDoc
types in the AVIF info class, and drop the note that asked for the
bump.
The new stubs type `WP_Block::$inner_blocks` as a `WP_Block_List`, so
the `empty()` check on it in the Navigation block is now reported as
never falsy, and is added to the baseline. Regenerating the baseline
also corrects the count of the `next_tag( 'img' )` error in the Image
block, which was already out of date on the base branch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Remove the AVIF type correction from the stubs generator
Since r65047, core's AVIF info class uses valid PHPDoc types, and the
recorded commit includes it, so the generator no longer rewrites its
`binary string` tags. Note why that step of generate.sh is left out.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Explain why the WordPress stubs are generated, and quiet the generator
`composer phpstan` generates the stubs whenever they are missing or out
of date, so its output began with the source being read, without
saying why. Lead with the reason instead: the stubs are missing, are
out of date with the recorded source, the generator, or the script, or
are generated again with `--force`.
The progress lines now say what each path is, and why a commit is
fetched from GitHub rather than read from a checkout. The generator's
own report, a title, the temporary file it wrote, and a table of
counts, duplicated these lines, so it is captured and left out, apart
from any duplicate declarations it lists. When the generator fails, its
output is shown.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Format the stubs generator's progress as aligned rows
The progress was a series of full sentences, with full commit hashes
and paths that wrapped across several lines. Show a heading with the
reason in parentheses instead, followed by labeled rows for the source,
the generator, and the result, with short commit hashes and no paths.
On a terminal, the heading is bold, the labels and details are dim, and
the check mark is green, unless NO_COLOR is set. FORCE_COLOR turns the
colors on elsewhere.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Share the commit hash check and the stubs heading
Check for a full commit hash in one helper, which both shortening a
hash for display and deciding whether to read a commit from the local
checkout use, and report the heading once, with a reason only when the
stubs are generated from the recorded source.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Name the pull request for uncommitted changes in the stubs source
With `--checkout --pr=<number>`, the source row left out the pull
request when the checkout had uncommitted changes, though it named it
otherwise, and the stub header and composer.json record it either way.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Show the commit that a pull request's head resolved to
When the stubs are generated from the head of a pull request, the ref
is only resolved to a commit once fetched, so the source row cannot
name the commit, and it was left out of the output entirely, though
composer.json records it. Add it to the done row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Give the full path of composer.json in the next step
The next step named `wordpress-stubs/composer.json`, which does not
resolve from the Gutenberg root, where Composer runs the script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Treat FORCE_COLOR=0 as turning colors off in the stubs generator
Any value of FORCE_COLOR turned colors on, including 0 and false, which
the Node.js tools in this repository treat as turning them off. Follow
them, and move the detection out of `style()` into `has_color()`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Name the generator's command when it fails
Since its output is captured, a failure of the generator was reported
only by its exit status. Name the command too, as the other commands
do when they fail, so that it can be run again by hand.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Show that the stubs are being generated while the generator runs
Since the generator's output is captured, its run, the longest step,
showed nothing after the generator's row, and could look hung. On a
terminal, show a row saying that the stubs are being generated, which
the done row then replaces in place. A log, where the replacement would
not show, gets no such row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Leave out the check mark when the stubs output has no colors
A Windows console with a legacy code page, or a log read in another
encoding, would garble the check mark. Show it only alongside colors,
where the terminal handles escape sequences, since the done row's label
already says the same.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Drop the redundant @var tag on the pending row flag
PhpStorm infers the type of the static flag from its initial value and
reports the tag as redundant, while PHPStan, which does not infer the
types of static variables, needed it to return a bool. Compare the flag
with true instead, which satisfies both.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Clear the pending stubs row explicitly, and share the row format
`is_pending()` both read and set whether a pending row was on the
current line, and `report()` cleared the row as a side effect, which
made both hard to follow. Instead, `report_pending_row()` returns
whether it wrote the row, and the caller clears it with
`clear_pending_row()` once the generator finishes, leaving no state to
share. Both kinds of row are formatted by `format_row()`, so that they
stay aligned.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Show the pending stubs row on a terminal, whether or not it has colors
Whether the pending row can be cleared depends on standard error being
a terminal, not on colors, so with FORCE_COLOR in CI it was written to
logs along with the escape sequence that clears it, and NO_COLOR on a
terminal left it out. Check for a terminal in `is_terminal()`, which
`has_color()` also falls back to.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Treat a dumb terminal as not handling escape sequences
A terminal that sets TERM=dumb, as some editors' shells do, got colors
and the escape sequence that clears the pending row anyway. Also stop
describing the color variables as working as in Node.js tools, which
give them a different precedence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep the stubs output to ASCII on Windows
Leaving out the check mark without colors did not cover a Windows
console that handles colors but uses a legacy code page, which garbles
the check mark and the ellipsis alike. On Windows, show neither: the
pending row ends with three periods, and the done row has no check mark.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Capture all of the generator's output, and leave out only its report
The generator's standard error was passed through while the pending
row was shown, so a warning would have been appended to the row, and
of its standard output, where the command-line PHP prints warnings,
only a list of duplicate declarations was kept, found by its heading.
Capture both streams together instead, and leave out only the report
the generator ends with, its title, the file it wrote, and its table of
counts, keeping what comes before and after it. Everything is kept when
the report is not found or the generator fails. On failure, nothing is
printed for empty output, and the multi-line header is left out of the
command in the error. The generator runs with `--no-ansi`, so that its
output holds no escape sequences.
PHPStan's signature of `proc_open()` does not allow the integer target
of a redirection, which PHP requires, so that error is ignored inline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Address LanguageTool nits
* Discard the generator's report rather than stripping it from its output
The report was found by matching its title and table borders, which
end in CRLF on Windows, where it never matched, and which depend on
the layout of symfony/console, which is not pinned. Its standard
output, which holds nothing but the report, is now discarded instead,
and only its standard error is shown, which PHP warnings go to as well
with `display_errors=stderr`. That is captured in a temporary file,
which cannot fill up and block the generator as a second pipe could.
This drops the list of duplicate declarations, which the generator
prints only in its report. Writing the stubs to standard output
instead of a file would avoid the report altogether, but the generator
prints them through Symfony Console, which strips the `</>` in the HTML
API's docblocks as a formatting tag.
Since nothing is redirected between descriptors anymore, PHPStan's
error about `proc_open()` no longer needs to be ignored.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Clear the pending stubs row when running the generator throws
When the generator could not be run at all, the exception skipped
clearing the pending row, so its message was printed on the same line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Decide once whether the stubs output has colors
`has_color()` read the environment again on every styled fragment,
several times a row. Cache its result, as `is_terminal()` does, and
read FORCE_COLOR only when NO_COLOR is not set.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Enable VT100 processing on Windows when FORCE_COLOR turns colors on
Only `is_terminal()` enabled VT100 processing on a Windows console,
which `has_color()` skips when FORCE_COLOR is set, so the console
showed the escape sequences as text.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use characters beyond ASCII in the stubs output only with a UTF-8 locale
Outside Windows, the ellipsis and check mark were used regardless of
the locale, so a terminal or log in a locale such as C or Latin-1
garbled them. Use them only when the locale, from LC_ALL, LC_CTYPE, or
LANG, is UTF-8.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Build the exception for a failed command in one place
The message naming a failed command was built in `run()`, in
`capture()`, and for the generator, which alone left out its multi-line
header. Build it in `command_failed()`, which leaves out a header for
any command.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Have clear_pending_row() check for a terminal itself
The caller had to keep whether `report_pending_row()` wrote the row,
and check it before clearing, or a log would get the escape sequence
that clears it. Both now check `is_terminal()`, which is cached, so the
pending row needs no state of its own.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Write the generator's standard error to a file in the work directory
`execute()` created the file for a command's standard error with
`tempnam()` while the pending row was shown, so a notice from it, such
as when the temporary directory is not writable, would have been
printed on the row. The caller now passes the file, which for the
generator is in the work directory that is removed on exit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Note that the generator's list of duplicate declarations is discarded
The comment on the generator's command said that its report of the
title, the file, and the counts is discarded, but not that the list of
the declarations it found more than once, of which the stubs keep the
first, goes with it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Name a checkout's commit by its branch rather than the repository
With `--checkout`, the source row named the commit after the
wordpress-develop repository, as though it were on GitHub, though it
may exist only in the checkout, which the stub header and composer.json
take care not to imply. Show the commit with the checkout's branch
instead, and the pull request it is for, if any.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Build the stubs done row from its parts
The done row was one expression of nested ternaries, styles, and
arithmetic, which made it hard to see what each case shows. Build its
details as a list, and name the elapsed time and check mark.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Decide once whether the stubs output can use characters beyond ASCII
Cache the result of `has_unicode()`, as its siblings `is_terminal()`
and `has_color()` do, rather than reading the locale again each time.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Turn colors on when FORCE_COLOR is set to an empty value
An empty FORCE_COLOR was treated as unset, though Node.js tools, run in
the same pipelines, take any FORCE_COLOR other than 0 or false, empty
included, to turn colors on.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Move the recorded source comment back to the return it describes
Building the done row from its parts put that code between the comment
on writing the recorded source and the early return that it explains.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Say that the stubs' elapsed time covers the whole run
The comment on the done row described its time as how long generating
took, though it is measured from before the source is fetched and the
generator is set up.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Decide once whether the stubs source is a ref to resolve
Whether the source was a ref rather than a commit hash was set in both
the branch that reads a commit from the checkout and the one that
fetches it, though the first already required a hash. Decide it once,
before either, and use it for that requirement too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Enable VT100 processing only in is_terminal()
When FORCE_COLOR turned colors on, `has_color()` enabled VT100
processing on a Windows console itself, repeating `is_terminal()`, but
without its check of TERM. Call `is_terminal()` for that instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Shorten any multi-line argument of a failed command
`command_failed()` left out a `--header` argument, which only the
generator's command has, so it carried knowledge of one caller. Shorten
any argument that spans several lines to its first line instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Show the declarations that the generator found more than once
Discarding the generator's report also discarded its list of the
declarations it found more than once. Of these, the stubs keep the
first, which may not be the one that PHPStan should see, such as when
core adds a polyfill or a compat shim, so the stubs could quietly have
the wrong signature.
The report now goes to a file, and the list is shown from its heading,
which comes from the pinned generator, rather than by matching the
layout of the report, which comes from Symfony Console and differs on
Windows. `execute()` writes both streams to files for this, replacing
the mode that only kept standard error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Drop an unnecessary cast of the generator's errors
Concatenation already turns a failed read into an empty string, as
PhpStorm points out, and PHPStan accepts it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Enable VT100 processing in a function of its own
When FORCE_COLOR turned colors on, `has_color()` called `is_terminal()`
only for its side effect of enabling VT100 processing on a Windows
console, which it skipped with TERM=dumb, so the console showed the
escape sequences as text. Both now call `enable_vt100()` directly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Treat an empty FORCE_COLOR as unset again
Turning colors on for an empty FORCE_COLOR followed Node.js tools, but
force-color.org counts FORCE_COLOR as set only when it is not empty,
as no-color.org does for NO_COLOR, which this script already follows.
Follow the written convention, so that both variables are read alike.
This reverts the behavior of 438d7e4ff0d.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep escape sequences out of the generator's report
Symfony Console assumes colors in some terminals, such as Git Bash on
Windows, even when writing to a file, so the list of duplicate
declarations taken from the generator's report could carry escape
sequences, even when this script uses no colors. Pass `--no-ansi`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Pass the files for a command's output as its mode
`execute()` had a mode for writing a command's output to files, and a
separate parameter for the files, which had to agree, as only an
exception at run time checked. Pass the files as the mode instead, so
that the two cannot disagree.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Update PHPStan to 2.3.4
The PHPStan extensions are already at their latest releases. With a
fresh build of trunk, the regenerated baseline is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Remove stale generator setups after setting up a new one
Each generator setup takes over 100 MB, and a new one is set up in a
directory of its own whenever the pinned generator commit or packages
change, leaving the old one behind for good. Once a new setup is in
place, remove the others. A branch that still pins one of them sets it
up again when it next generates the stubs.
Only directories named like a setup are removed, since the cache
directory can be overridden with one that holds other things, and a
setup still in progress, under a name starting with a period, is kept.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Prune only generator setups that have not been used for a week
Removing every other setup as soon as a new one was installed meant
that switching between branches with different pins, such as trunk and
a branch that changes them, reinstalled the generator on every switch.
Touch a setup's directory whenever it is used, so that its time is
when it was last used rather than when it was installed, and remove the
other setups that have not been used for a week. A setup's directory
time is otherwise only set once, when it is moved into place. Since a
setup can go unused without a new one being installed, this happens
whenever the stubs are generated, the only time the generator is used.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: justlevine <justlevine@git.wordpress.org>
Co-authored-by: westonruter <westonruter@git.wordpress.org>
Co-authored-by: apermo <apermo@git.wordpress.org>
Co-authored-by: szepeviktor <szepeviktor@git.wordpress.org>
Co-authored-by: anton-vlasenko <antonvlasenko@git.wordpress.org>
Co-authored-by: ramonjd <ramonopoly@git.wordpress.org>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What?
Closes #66598
This adds PHPStan static analysis to Gutenberg, at rule level 5, with a baseline for the existing errors, and runs it in CI. It covers the plugin's own PHP and all the PHP that WordPress core ships from this repository, including the
wp-buildPHP templates.Why?
WordPress core has run PHPStan since Core-61175, and is now at rule level 5. Much of core's PHP comes from Gutenberg, though, and core cannot analyze the most important part of it: the block PHP,
core-fields,core-actions, and the PHP generated from thewp-buildtemplates are copied into core verbatim and excluded from core's analysis, since they are generated there. Gutenberg is the only place this code can be analyzed, because it is the only place it can be fixed.For the PHP in
lib/that is backported to core, analyzing it here catches problems before they reach core, and keeps the two codebases in sync as fixes are made on either side. The PHPStan fixes that preceded this PR (#68386, #68389, #68392, #68396, #68397, #68398, #68399, #68401, #68404, #68405, #68407) found, among others, a bug in core's shadow block support and a fatal error inWP_Theme_JSON::get_feature_declarations_for_node(), both since fixed in core in r64727.How?
This was originally opened by @justlevine with per-level baselines and custom handling for the generated functions. It has been reworked to follow core's setup more closely:
szepeviktor/phpstan-wordpress2 and the WordPress stubs (see below). As in core, these are pinned to exact versions: there is no Composer lock file, so a new release of PHPStan or of the stubs could otherwise change the results and fail CI on every pull request at once, whereas pinned, an upgrade is a deliberate change that regenerates the baseline. The Composer scripts arecomposer phpstanandcomposer phpstan:baselines, and the npm scriptstypecheck:phpandtypecheck:php:baselinesrun them inwp-env, aslint:phpdoes for PHPCS; all four are named as in core. The baretypecheckscript remains the TypeScript check, since it runs in CI and in editor workflows withoutwp-env, the waylintdoes not includelint:php.phpstan.neon.distsets level 5, as core does, with the 226 existing errors in one standardtools/phpstan/baseline.neon.reportUnmatchedIgnoredErrorsis on, so a fixed error has to be removed from the baseline too.composer phpstan:baselinesalways usesphpstan.neon.dist, so a localphpstan.neon, such as one with a higher level, can never end up in the baseline.phpunit/are not analyzed by default, since they do not ship in core, butphpstan/phpstan-phpunit, which core also uses, andphp-stubs/wordpress-tests-stubs, for the WordPress test library thatwp-envprovides at runtime, are installed. A localphpstan.neonthat addsphpunitto the paths can opt in to them, as the coding guidelines show.phpVersioncovers PHP 7.4 through 8.5, so the results do not depend on the PHP version PHPStan runs on, andtreatPhpDocTypesAsCertainisfalse, since PHPDoc types are not enforced at runtime.gutenberg.phpandlib/, plus the PHP inblock-library, the widget blocks,core-fields,core-actions,style-engine,block-serialization-default-parser, andicons.lib/calls manygutenberg_*functions and*_Gutenbergclasses that only exist once the build has renamed them intobuild/. That directory is scanned, so they are known with their real signatures, and the original ignore rule for unknowngutenberg_*functions is no longer needed. This meansnpm run buildhas to run beforecomposer phpstan.php-stubs/wordpress-stubspublishes stubs built from trunk,tools/phpstan/generate-wordpress-stubs.phpgenerates them with its generator, currently from core trunk at r65047. The generator is pinned to the head of Override Core PHPStan tags and recommend redundant map annotations php-stubs/wordpress-stubs#498, without which it adds a second@phpstan-returnto the docblocks that now have their own in core, and the packages that determine its output, such as nikic/php-parser and phpdocumentor/reflection-docblock, are pinned to exact versions, so that a new release of one cannot change the stubs without a commit here. The stubs live intools/phpstan/wordpress-stubs/as a Composer path package namedphp-stubs/wordpress-stubs, which replaces the released package, sinceszepeviktor/phpstan-wordpressloads the stubs from that package's path. The path repository symlinks it, since the stubs are generated after Composer installs the package. The stubs themselves are not committed. At 6.3 MB, every update would carry them as a diff. Instead, the package'scomposer.jsonrecords the source they are generated from, andcomposer phpstangenerates them before analyzing, returning at once when they are up to date. The stub header records a key for the source, the generator, its pinned packages, and the script itself, so a pull that changes any of them generates the stubs again. Generating needs Git, and network access unless the commit is in the wordpress-develop checkout that Gutenberg is in. The script is written in PHP rather than Bash, since every contributor who runs PHPStan now runs it, including on Windows. The generator is set up once in.cache/wordpress-stubs-generator/, in a directory named for its commit and pinned packages, and setups that have not been used for a week are removed. While generating, the script reports the source, the generator, and the result in a few rows, along with the generator's warnings and any declarations it found more than once, of which the stubs keep the first. When the stubs are missing, such as whenvendor/bin/phpstanis run directly, as an IDE does,wordpress-stubs.phpthrows an exception explaining how to generate them. The source is changed with an option ofcomposer phpstan:generate-wordpress-stubs:--commit=<ref>, such astrunk;--pr=<number>, for the head of a wordpress-develop pull request; or--checkout, for the working tree of the wordpress-develop checkout, including uncommitted changes. Stubs generated from uncommitted changes are only used locally, since CI cannot reproduce them, so they have to be generated with--pror--commitbefore pushing. This supports companion pull requests: a Gutenberg change that depends on a wordpress-develop pull request records it as the source, so that the analysis knows what it adds, and switches to--commit=trunkonce the core change is committed. After changing the source, runcomposer updateandcomposer phpstan:baselines, and commit the package'scomposer.json. Scanning the checkout'ssrc/directly was also tried, since PHPStan prefers scanned declarations to the stubs, but the stubs are not a plain copy of core: the generator adds the types from the function map ofwordpress-stubs, so against rawsrc/, 32 baseline entries no longer matched and 2 new errors were reported. Core's global type aliases, which the stubs could not carry, were removed in r64756 for this, and the invalid PHPDoc types in core's AVIF info class, which the generator had to correct, were fixed in r65047. Generating the stubs here is meant to be temporary; see the roadmap below.wp_get_elements_class_name()requires in 7.0 but no longer takes, and themethod_exists()guard for aWP_REST_Comments_Controllermethod added in 7.2. The flip side is that calling something added since 7.0 without a guard is not reported.tools/phpstan/polyfills.stubdeclares the polyfills that WordPress trunk provides for newer PHP functions, such asstr_contains(),array_any(), andclamp(). The stubs leave outcompat.php, and could not include it, since they are executed as a bootstrap file, where a polyfill would redeclare a function the running PHP has.wp-buildtemplates: these contain{{PLACEHOLDER}}tokens, so they are not valid PHP until the build replaces them.tools/phpstan/src/WpBuildTemplateParser.phpwraps the parsers PHPStan uses for analyzed files and for discovering the functions a file declares, and substitutes a representative value for each token first. No substitution spans more than one line, so errors, including syntax errors, are reported on the template lines themselves rather than on each file generated from them. The templates are rendered with a prefix that no built file uses, so that a call in a template resolves to the template's own function rather than to the one built from it inbuild/, which may be out of date.PHP static analysisjob in the unit test workflow reuses thebuild-assetsartifact that the PHP unit test jobs already download, so the build does not run twice. Errors are reported as annotations on the pull request, and the job is part of the status check. Since an annotation only appears in the diff when its line was changed, and GitHub shows at most ten per step, the job summary also lists every error with a link to its line, up to 500, with the errors that belong to no file first, and explains an out-of-date baseline, the usual error with no changed line to attach to: when a baselined error occurs fewer times, it is expected after fixing it, andcomposer phpstan:baselinesresolves it, unless other errors are reported too, which are to be fixed first; when it occurs more times, the pull request likely added an occurrence, which should be fixed rather than baselined. The generated stubs are cached by their recorded source and the script, restored in every run, and saved only on pushes to trunk; on a miss, the job generates them, which takes about 25 seconds. The PHPStan result cache is likewise restored in every run, but only saved on pushes to trunk, since a cache saved for a pull request could only be restored by that pull request. It is keyed on the configuration, dependencies, and generated stubs, but not the baseline, which does not change the analysis. Unlike in core, errors stay errors rather than warnings, since Gutenberg merges on GitHub and relies on its checks to keep new errors out. Zizmor reports every cache in this workflow as open to cache poisoning, including those the PHP unit test and PHPCS jobs already restore, because it runs on pushes to therelease/*branches and so is taken to be a release workflow. Nothing built in it is published, so that finding is ignored, with the reasoning in a comment on thepushtrigger. The version comments on theramsey/composer-installpins are also corrected to4.0.0, the tag the pinned commit has.Follow-ups
This PR analyzes the PHP that ships, in the plugin and in core. The rest of the PHP in the repository could be analyzed in follow-up PRs:
phpunit/, which can already be opted in to locally. At level 5, they add only a few errors to the baseline.packages/e2e-tests/pluginsandpackages/e2e-tests/mu-plugins, whichwp-envloads for the end-to-end tests.test/php/gutenberg-coding-standards, which would need the PHPCS classes invendorto be scanned.wp-envruntime:packages/env/lib/runtime/php/install.phpandrouter.php, which are new in trunk.test/emptythemeandtest/gutenberg-test-themes, andtools/validation/fixtures/theme-compatibility/theme-compatibility.php.test/test-parser.phpinblock-serialization-default-parser, which is excluded on purpose for now, and inblock-serialization-spec-parser.tools/phpstan, including the template parser.The analysis of code for older WordPress versions could also be improved:
@sinceis newer than the plugin'sRequires at least, outside afunction_exists()guard, along with the functions that Gutenberg itself declares, such as those inlib/compat, and report the calls to functions that Gutenberg does not declare. The polyfills intools/phpstan/polyfills.stubwould get@sincetags for it, and methods and classes could be checked the same way, with theirmethod_exists()andclass_exists()guards.Roadmap for the WordPress stubs
Generating the stubs in Gutenberg is a stopgap. The goal is for
php-stubs/wordpress-stubsto publish the stubs Gutenberg needs, so that Gutenberg can require them like any other dependency:@phpstan-returnto the docblocks that now have their own in core. Until it is merged, the generator is pinned to the head of that PR, and then to the release that includes it.wordpress-stubspublish stubs built from core trunk, such as nightly. Each build needs to be pinnable, ideally by a version of its own derived from the SVN revision, like the7.2.0-beta3.65047used here, or at least by commit. A movingdev-branch alone would not do: Gutenberg has no Composer lock file, so a floating build would let any change in core trunk fail the analysis on every pull request at once.tools/phpstan/generate-wordpress-stubs.php, thetools/phpstan/wordpress-stubs/package and its path repository incomposer.json, thephpstan:generate-wordpress-stubsscript and its call incomposer phpstan, and the steps that cache and generate the stubs in CI.tools/phpstan/polyfills.stubstays, since the upstream stubs also leave outcompat.php, as they are executed as a bootstrap file, and so do the inline ignores for WordPress 7.0, since the stubs are still newer than the minimum supported version. Generating stubs from a core pull request, for companion pull requests, would still need the generator, unless the upstream builds cover pull requests too, so a slimmed-down script may be kept for that alone.composer phpstan:generate-wordpress-stubs -- --commit=trunkinstead.Testing Instructions
composer installandnpm run build. Have Git available, and network access unless Gutenberg is in a wordpress-develop checkout that has r65047.composer phpstan, and confirm that it first generates the WordPress stubs intools/phpstan/wordpress-stubs/, then reports no errors. Run it again, and confirm that it skips generating them.str_contains()in a file inlib/, and confirm that it is reported. Do the same in a template inpackages/wp-build/templates, and confirm that the error is reported on the template line.tools/phpstan/baseline.neon, and confirm that the error it covered is reported again. Then runcomposer phpstan:baselines, and confirm that the entry is restored.PHP static analysisjob passes in CI.Testing Instructions for Keyboard
Not applicable, since there are no UI changes.
Screenshots or screencast
Initial PHPStan run
This shows the worst case, where
wordpress-stubsneeds to be installed and the stubs need to be generated:run-with-stub-install-and-stub-generation.mov
PHPStan run with stale wordpress-stubs
This shows where
wordpress-stubsis installed, but the stubs need to be re-generated:run-with-stub-generation.mov
PHPStan run with with stubs generated
This is the normal case where the stubs are already generated:
run-with-stubs-cached.mov
Use of AI Tools
The rework was done with Claude Code (Claude Opus 5.5): upgrading the configuration, writing the template parser and the polyfill stubs, generating the WordPress stubs from core trunk, and on demand with a PHP generator, adding the CI job, regenerating the baseline, and drafting the commit messages and this description, under the direction and review of @westonruter.
🤖 Generated with Claude Code