You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Adds phpstan-strict-rules as a development dependency, and enables by default the rules that the code already complies with, as WordPress core now does.
Why?
These rules already pass, so enabling them keeps new code from regressing on them. Several also back up rules of the WordPress Coding Standards: the loose comparison rule backs Universal.Operators.StrictComparisons, the short ternary rule Universal.Operators.DisallowShortTernary, the backtick rule Generic.PHP.BacktickOperator, and the strict function calls rule WordPress.PHP.StrictInArray. The rules that are not enabled can be tried in a local phpstan.neon to work toward complying with them.
How?
Each rule group was measured with every strict rule enabled over phpstan.neon.dist. These are enabled, and report no errors:
Disallow short ternaries (disallowedShortTernary).
Disallow $this in closures (closureUsesThis).
Require inherited method names to match in case (matchingInheritedMethodNames).
Require switch case types to match the condition (switchConditionsMatchingType).
Disallow calling a constructor as a method (illegalConstructorMethodCall).
Require the strict argument of in_array(), array_search(), array_keys(), and base64_decode() (strictFunctionCalls). Its one error was the Legacy Widget block's base64_decode() call, which now decodes in strict mode. The block now also requires the encoded and hash values of its instance attribute to be strings, rendering nothing otherwise, since a non-string encoded made base64_decode() throw a TypeError on PHP 8. A value the editor encoded decodes as before.
The rules are registered individually in phpstan.neon.dist, rather than by including the package's rules.neon, because that file also makes several PHPStan parameters stricter, such as checkDynamicProperties and reportMaybesInMethodSignatures, even when its rules are disabled. Unlike core, Gutenberg uses phpstan/extension-installer, which would include rules.neon automatically, so composer.json tells it to ignore the package. The loose comparison rule takes an argument, so it is registered as a service with the value rules.neon gives it.
The coding guidelines document how to opt into the other rules with a local phpstan.neon. That example was tested to load and report only the rules it enables, along with the errors from the stricter parameters.
Follow-up candidates
These were evaluated and left for later:
numericOperandsInArithmeticOperators reports no errors, and catches arithmetic on non-numeric values that level 5 lets through. Its rules need an OperatorRuleHelper service, which rules.neon registers. Registering one in phpstan.neon.dist would leave two once a local config includes rules.neon, and PHPStan then fails to load the configuration with "Multiple services of type PHPStan\Rules\Operators\OperatorRuleHelper found". It can be enabled by registering a helper with autowired: false and the ten rules as services passed that helper explicitly, so that the one from rules.neon stays the only autowired one.
dynamicCallOnStaticMethod has three errors, all $this->process_blocks_custom_css() calls to a public static method in WP_Theme_JSON_Gutenberg, which static:: fixes. Core's WP_Theme_JSON has the same three calls, so they are best fixed in core as well, and the rule enabled once the class is synced.
These are not worth enabling for now:
Rule
Errors
Reason
requireParentConstructorCall
1
WP_Icons_Registry_Gutenberg::__construct() skips the parent constructor on purpose, as its docblock explains.
overwriteVariablesWithLoop
1
Two consecutive foreach ( … as &$node ) loops in WP_Theme_JSON_Gutenberg, which is safe since both are by reference.
uselessCast
2
One is an (int) cast of a printf() argument that WPCS counts as escaping it.
strictArrayFilter
6
array_filter() without a callback is idiomatic, and the calls are in package PHP that core also ships.
noVariableVariables
5
Variable property access, such as $post->$field, is a legitimate pattern here.
booleansInConditions
about 300
Too many to address in one change.
disallowedEmpty
812
empty() is idiomatic in WordPress, and WPCS does not discourage it.
Testing Instructions
Run composer update, then npm run build and composer phpstan. No errors are reported.
Add a loose comparison such as if ( $a == 'x' ) to a file in lib/, and run composer phpstan again. It is reported as equal.notAllowed.
Create a phpstan.neon with the example from the coding guidelines, and run composer phpstan. The configuration loads, and only the opted-in rules, plus the stricter parameters of rules.neon, report errors.
For the Legacy Widget block, add a legacy widget, such as a Text widget, in the widgets editor or a post, save, and check that it still renders on the front end.
Use of AI Tools
Written with Claude Code using Claude Opus 5.5 (medium effort): measuring which strict rules the code complies with, testing the configuration and the local opt-in example, and writing the configuration, documentation, and Legacy Widget changes, all reviewed by me.
The analysis reports no errors with this release, and no baseline entry
goes stale, so the baseline is unchanged. The other PHPStan packages,
phpstan-phpunit (2.1.1), extension-installer (1.4.3), and
szepeviktor/phpstan-wordpress (2.0.4), are already at their latest
versions.
The `WP_REST_Request` offset ignores stay, since the PHPStan fix they
wait on (phpstan/phpstan-src#6903) is not yet merged.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
PHPStan 2.3.5 can fix stale ignores itself: `--fix` lowers a baseline
count that is now too high, removes an entry that matches nothing, and
removes an `@phpstan-ignore` comment that no longer ignores anything.
Verified on `tools/phpstan/baseline.neon`: an inflated count was lowered
back to its real value, leaving the rest of the file as it was.
That suits Gutenberg better than regenerating. `composer
phpstan:baselines` is PHPStan's `--generate-baseline`, which records
every error the run reports, so the job summary had to warn against
regenerating while other errors were still reported. `--fix` never adds
an entry, so it is safe to run then too.
The coding guidelines and the job summary now recommend `--fix`, and
explain that it has to be a run over all the paths, since PHPStan
reports no out-of-date entries when it analyzes only some files.
`report.ts` also reads the `fixable` flag that PHPStan's JSON report now
carries: an annotation of a fixable error says how to fix it, and the
job summary marks the error with 🔧, as PHPStan's table output does.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
As WordPress core now does, this adds phpstan/phpstan-strict-rules as a
development dependency, and enables by default the rules the code
already complies with, so that they are kept to:
* Disallow loose comparisons.
* Disallow the backtick operator.
* Disallow implicit array creation.
* Disallow short ternaries.
* Disallow `$this` in closures.
* Require inherited method names to match in case.
* Require switch case types to match the condition.
* Disallow calling a constructor as a method.
Each was measured with every strict rule enabled over
`phpstan.neon.dist`, and reports no errors.
The rules are registered individually rather than by including the
package's `rules.neon`, because that file also makes several PHPStan
parameters stricter even when its rules are disabled. Unlike core,
Gutenberg uses phpstan/extension-installer, which would include
`rules.neon` automatically, so composer.json tells it to ignore the
package. The loose comparison rule takes an argument, so it is
registered as a service, with the value `rules.neon` gives it.
The arithmetic operand rules also report no errors, but are left out:
they need an `OperatorRuleHelper` service, and registering one would
leave two once a local config includes `rules.neon`, which PHPStan then
fails to load. The useless cast rule has only two errors, but one of
them is a `(int)` cast that WPCS counts as escaping a `printf()`
argument.
The coding guidelines document how to opt into the other rules with a
local `phpstan.neon`, which was tested to load and report only the rules
it enables, along with the errors from the stricter parameters. The
`phpstan.neon.dist` header now says to include the file rather than copy
it, as core's does.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
The `instance` attribute is only validated as an object, so its nested
`encoded` and `hash` values can be of any type. A non-string `encoded`
made `base64_decode()` throw a TypeError on PHP 8. Both are now required
to be strings, and the block renders nothing otherwise, as it does for a
hash that does not match. That also makes the `(string)` cast of the
hash unnecessary.
Without its `$strict` argument, `base64_decode()` silently skips
characters outside the base64 alphabet, so a malformed `encoded` value
still decoded to some bytes, which then failed the hash check. In strict
mode it returns false instead, which is now checked explicitly, so that
false is never passed to `wp_hash()`. A value the editor encoded decodes
exactly as before.
This is the one call in the analyzed code that phpstan-strict-rules'
`StrictFunctionCallsRule` reports, which is enabled next.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
`StrictFunctionCallsRule` requires the strict argument of `in_array()`,
`array_search()`, `array_keys()`, and `base64_decode()`. For the first
three it is also enforced by the WordPress.PHP.StrictInArray sniff of
the WordPress Coding Standards, and with the legacy widget's
`base64_decode()` call now strict, the code complies with it.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.
Navigates the items list via UP/DOWN arrow keys in /test/e2e/specs/site-editor/dataviews-list-layout-keyboard.spec.js, passed after 1 failed attempt.
Error: expect(locator).toBeFocused() failed
Locator: getByLabel('Page Two')
Expected: focused
Received: inactive
Timeout: 5000ms
Call log:
- Expect "toBeFocused" getByLabel('Page Two') with timeout 5000ms
- waiting for getByLabel('Page Two')
14 × locator resolved to <button type="button" tabindex="-1" aria-pressed="false" id="view-list-0-184-item-wrapper" class="dataviews-view-list__item" aria-labelledby="view-list-0-184-label" aria-describedby="view-list-0-184-description"></button>
- unexpected value "inactive"
at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/dataviews-list-layout-keyboard.spec.js:146:49
does not select blocks in the canvas preview when editing from the sidebar in /test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js, passed after 1 failed attempt.
Error: expect(locator).toBeFocused() failed
Locator: getByRole('combobox', { name: 'Search or type URL' })
Expected: focused
Timeout: 5000ms
Error: element(s) not found
Call log:
- Expect "toBeFocused" getByRole('combobox', { name: 'Search or type URL' }) with timeout 5000ms
- waiting for getByRole('combobox', { name: 'Search or type URL' })
at LinkControl.useLinkControlSearch (/home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js:416:47)
at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js:179:21
Resolves the conflict in the coding guidelines, where trunk split the
PHPStan paragraph into subsections. Trunk's structure is kept, and the
recommendation of `--fix` for out-of-date baseline entries is applied
to its "The baseline" subsection.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
Brings in trunk by way of the base branch, which was merged with it.
The analysis still reports no errors with the strict rules enabled.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
Trunk split the PHPStan section of the coding guidelines into
subsections, so the strict rules paragraph, written as part of the
single paragraph before, now follows the local configuration example.
It gets a "Strict rules" subsection of its own, and links
`phpstan.neon.dist` as the other subsections do.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
Tested the Legacy Widget decoding change on PHP 8.3. Strict base64_decode() decodes valid encodings to the same bytes as the loose mode, including with 76-column line breaks, a trailing newline and surrounding spaces, so existing encoded instances keep decoding as before. Input that isn't base64 now returns false at decode instead of reaching the hash_equals() check; it rendered nothing before either, so there's no visible change. I didn't test the strict rules themselves.
Removing an out-of-date baseline entry meant running
`composer phpstan -- --fix`. Leaving out the `--` makes Composer discard
the flag silently, so the analysis just reports the stale entries again.
`composer phpstan:fix` (and `npm run typecheck:php:fix`) chains two
steps, the second run only when the first succeeds:
* PHPStan with `--fix`, which lowers or removes the stale entries.
* The analysis once more, since PHPStan's `--fix` reports only what it
fixed, and succeeds even when other errors remain. It reuses the
result cache, so it is quick.
Both analyses use `phpstan.neon.dist`, whatever a local `phpstan.neon`
says. A configuration at another rule level can report a baselined error
with a different message, and `--fix` then removes entries the default
configuration still needs.
When nothing is fixable, PHPStan exits with 1 and stops the chain, which
the coding guidelines note.
The coding guidelines, the README, and the CI annotation and job summary
now point to the new scripts.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
The comment above the baseline include in `phpstan.neon.dist` still
recommended `composer phpstan -- --fix`.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
The change alters published @wordpress/widgets runtime behavior without the required Unreleased changelog entry documenting the consumer-visible Legacy Widget fix.
Adds phpstan-strict-rules to Gutenberg’s development tooling and enables the rules already satisfied by the codebase, while hardening Legacy Widget instance decoding against invalid input.
Changes:
Registers supported strict PHPStan rules individually and prevents automatic loading of the package’s broader configuration.
Documents how contributors can opt into additional strict rules locally.
Uses strict Base64 decoding and validates Legacy Widget instance values before rendering.
File
Description
phpstan.neon.dist
Enables compatible phpstan-strict-rules checks and registers them individually.
The render callback of the Legacy Widget block now renders nothing for an
`instance` attribute whose `encoded` or `hash` value is not a string,
where `base64_decode()` or `hash_equals()` previously caused a fatal
error. It also decodes in strict mode, rejecting characters outside the
base64 alphabet. Both change what consumers of the package see for
malformed attributes, so they get a Bug Fixes entry.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
On PHP 7.4, `base64_decode()` and `hash_equals()` only emit a warning for
a value of the wrong type, and the hash check then fails, so the block
already rendered nothing there. The `TypeError` that crashed rendering
is thrown only on PHP 8, which the changelog entry now says.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
Only an array `encoded` value made `base64_decode()` throw a `TypeError`.
The `hash` value was already cast to a string before `hash_equals()`, so
a non-string `hash` caused at most an "Array to string conversion"
warning, and the block rendered nothing. The changelog entry claimed both
values could cause the error.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
Decoding `encoded` in strict mode changes nothing a consumer can see.
Without it, `base64_decode()` skips characters outside the base64
alphabet, so a value with stray characters decodes to the same bytes as
the clean value, passes or fails the hash check just as that value would,
and renders the same instance. The `true` argument is there for the
`strictFunctionCalls` rule, so the entry keeps only the `TypeError` fix.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
Decoding `encoded` in strict mode is visible to consumers after all.
Without it, `base64_decode()` skipped characters outside the base64
alphabet, so a value with stray characters decoded to the clean bytes,
passed the hash check, and the widget rendered. Strict mode now returns
false for such a value, which renders nothing before the hash is checked.
Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tnky3GdCg3QL5KeMvuQvwf
Claude-Code-Session-Id: 5bac4eea-faaa-40e6-8440-b696b7773ba6
So the is_string() check for the encoded value is the main fix here.
The addition of the strict param further validates that the string is valid base64 data. Since there's also a hash check on the decoded data, it's not really important. But it shouldn't hurt. It would only impact blocks where someone intentionally added stray non-base64 chars to the base64 data.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
Focused PHPUnit tests are still needed to verify that array and non-base64 encoded inputs are safely rejected while valid encoded instances continue to render.
No open issues 🎉
1 previously missed issue
In code that hasn't changed since last review
Add tests for malformed and valid encoded widget instances
The new malformed-input paths are untested: an array encoded value must return an empty render instead of throwing, and a non-base64 character must be rejected while a valid encoded instance still renders. The repository has PHPUnit coverage for comparable block render callbacks, so please add focused tests for these branches.
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
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?
Follow up to #86333, which this is stacked on. The WordPress core counterpart is WordPress/wordpress-develop#15399, committed in r65265.
Adds phpstan-strict-rules as a development dependency, and enables by default the rules that the code already complies with, as WordPress core now does.
Why?
These rules already pass, so enabling them keeps new code from regressing on them. Several also back up rules of the WordPress Coding Standards: the loose comparison rule backs
Universal.Operators.StrictComparisons, the short ternary ruleUniversal.Operators.DisallowShortTernary, the backtick ruleGeneric.PHP.BacktickOperator, and the strict function calls ruleWordPress.PHP.StrictInArray. The rules that are not enabled can be tried in a localphpstan.neonto work toward complying with them.How?
Each rule group was measured with every strict rule enabled over
phpstan.neon.dist. These are enabled, and report no errors:disallowedLooseComparison).disallowedBacktick).disallowedImplicitArrayCreation).disallowedShortTernary).$thisin closures (closureUsesThis).matchingInheritedMethodNames).switchConditionsMatchingType).illegalConstructorMethodCall).in_array(),array_search(),array_keys(), andbase64_decode()(strictFunctionCalls). Its one error was the Legacy Widget block'sbase64_decode()call, which now decodes in strict mode. The block now also requires theencodedandhashvalues of itsinstanceattribute to be strings, rendering nothing otherwise, since a non-stringencodedmadebase64_decode()throw aTypeErroron PHP 8. A value the editor encoded decodes as before.The rules are registered individually in
phpstan.neon.dist, rather than by including the package'srules.neon, because that file also makes several PHPStan parameters stricter, such ascheckDynamicPropertiesandreportMaybesInMethodSignatures, even when its rules are disabled. Unlike core, Gutenberg usesphpstan/extension-installer, which would includerules.neonautomatically, socomposer.jsontells it to ignore the package. The loose comparison rule takes an argument, so it is registered as a service with the valuerules.neongives it.The coding guidelines document how to opt into the other rules with a local
phpstan.neon. That example was tested to load and report only the rules it enables, along with the errors from the stricter parameters.Follow-up candidates
These were evaluated and left for later:
numericOperandsInArithmeticOperatorsreports no errors, and catches arithmetic on non-numeric values that level 5 lets through. Its rules need anOperatorRuleHelperservice, whichrules.neonregisters. Registering one inphpstan.neon.distwould leave two once a local config includesrules.neon, and PHPStan then fails to load the configuration with "Multiple services of typePHPStan\Rules\Operators\OperatorRuleHelperfound". It can be enabled by registering a helper withautowired: falseand the ten rules as services passed that helper explicitly, so that the one fromrules.neonstays the only autowired one.dynamicCallOnStaticMethodhas three errors, all$this->process_blocks_custom_css()calls to apublic staticmethod inWP_Theme_JSON_Gutenberg, whichstatic::fixes. Core'sWP_Theme_JSONhas the same three calls, so they are best fixed in core as well, and the rule enabled once the class is synced.These are not worth enabling for now:
requireParentConstructorCallWP_Icons_Registry_Gutenberg::__construct()skips the parent constructor on purpose, as its docblock explains.overwriteVariablesWithLoopforeach ( … as &$node )loops inWP_Theme_JSON_Gutenberg, which is safe since both are by reference.uselessCast(int)cast of aprintf()argument that WPCS counts as escaping it.strictArrayFilterarray_filter()without a callback is idiomatic, and the calls are in package PHP that core also ships.noVariableVariables$post->$field, is a legitimate pattern here.booleansInConditionsdisallowedEmptyempty()is idiomatic in WordPress, and WPCS does not discourage it.Testing Instructions
composer update, thennpm run buildandcomposer phpstan. No errors are reported.if ( $a == 'x' )to a file inlib/, and runcomposer phpstanagain. It is reported asequal.notAllowed.phpstan.neonwith the example from the coding guidelines, and runcomposer phpstan. The configuration loads, and only the opted-in rules, plus the stricter parameters ofrules.neon, report errors.Use of AI Tools
Written with Claude Code using Claude Opus 5.5 (medium effort): measuring which strict rules the code complies with, testing the configuration and the local opt-in example, and writing the configuration, documentation, and Legacy Widget changes, all reviewed by me.