Repository navigation
REST API: Accept a post object in the global styles controller's prepare_links() - #15826
westonruter wants to merge 14 commits into
Conversation
…are_links() `WP_REST_Global_Styles_Controller::prepare_links()` overrides `WP_REST_Posts_Controller::prepare_links( $post )` but took a post ID instead of a `WP_Post`, which PHPStan reports as an incompatible child parameter type. Widen the parameter to `WP_Post|int`, so it accepts what the parent method does while still accepting an ID, and pass the post object from `prepare_item_for_response()`. Also give the links array a value type. Remove the corresponding baseline entry. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
`get_rest_url()` always builds a non-empty URL: the home URL followed by the REST prefix and a route that starts with `/`, or by `index.php` with a `rest_route` query arg. Document the contract with `@phpstan-return non-falsy-string` on it and on `rest_url()`, and with a `@phpstan-param non-falsy-string` for `$url` on the `rest_url` filter, so that the filtered value is typed by the same contract. This lets callers pass REST URLs where a non-empty string is required, such as the `href` of a link given to `WP_REST_Response::add_links()`. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
`WP_Query::$found_posts` is a count of rows, so document it as `int<0, max>`, matching `$max_num_pages`. The count is set from `FOUND_ROWS()`, from the number of posts, or from the `found_posts` filter. Document the filter's `$found_posts` as `int<0, max>` too, and clamp the result of the `found_posts_query` query to zero, as is already done for `$max_num_pages`, since that query is itself filterable. `wp_get_latest_revision_id_and_total_count()` returns the count from `$found_posts`, so its `count` is now `int<0, max>` as well. Regenerate the baseline: the existing `header()` errors for `X-WP-Total` now report `int<0, max>` instead of `int`. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
Narrow the return type of `WP_REST_Global_Styles_Controller::prepare_links()` to the links it builds: `self` and `about`, plus `version-history` with its revisions `count` when the post type supports revisions. For `prepare_item_for_response()` to pass these links to `WP_REST_Response::add_links()`, the `count` link attribute is declared in the `Link_Attributes` and `Link_Input` types, as a non-negative integer. It is also used for `version-history` links by the posts and templates controllers. Declaring it is needed because PHPStan merges `Link_Input` with its list form in `add_links()` and drops the unsealed keys, so an attribute not named in the shape is rejected when a caller passes a precise shape. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
Test using WordPress PlaygroundThe changes in this pull request can previewed and tested using a WordPress Playground instance. WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser. Some things to be aware of
For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation. |
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. Core Committers: Use this line as a base for the props when committing in SVN: To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
|
There was a problem hiding this comment.
🟡 Changes recommended
Active moderate findings show that filtered query results can still produce negative revision counts, violating the intended non-negative contract and affecting the emitted version-history count.
2 open issues
What changed in this PR
This pull request updates the global styles REST controller to accept WP_Post objects consistently with its parent controller while adding stricter PHPStan types for REST links, revision counts, URLs, and query totals.
Changes:
- Passes post objects to
prepare_links()while retaining integer ID compatibility. - Adds structured link return types and typing for non-negative link counts.
- Updates REST URL, revision-count, and query-count annotations.
- Regenerates the affected PHPStan baselines.
The review identified unresolved issues involving negative filtered query counts and the non-falsy-string REST URL contract.
This pull request requires changes.
| File | Review summary |
|---|---|
tests/phpstan/baselines/method.childParameterType.neon |
Removes the resolved global styles parameter-compatibility baseline entry. |
tests/phpstan/baselines/argument.type.neon |
Regenerates baseline entries for refined integer types. |
src/wp-includes/revision.php |
Adds a typed revision ID and count return contract. Moderate issue (2 votes): filtered negative found_posts values can still produce a negative revision count. |
src/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php |
Accepts post objects in link preparation and documents the returned link structure. |
src/wp-includes/rest-api/class-wp-rest-response.php |
Adds typed support for non-negative count link attributes. |
src/wp-includes/rest-api.php |
Documents REST URL values as non-falsy strings. Nit (1 vote): the filter can return an empty string, making the contract unsound for callers after filtering. |
src/wp-includes/class-wp-query.php |
Adds query count typing and clamps negative database totals. Moderate issue (3 votes): the found_posts filter runs after the clamp and can still return a negative value. |
Review effort: Lite
`WP_Query::$found_posts` is documented as `int<0, max>`, but the `found_posts` filter runs after the `FOUND_ROWS()` result is clamped, so a filter returning a negative number still made the count negative. That value then reached the `X-WP-Total` header and, through `wp_get_latest_revision_id_and_total_count()`, the `count` of `version-history` links. Clamp the filtered value to zero as well, as is already done for `$max_num_pages`, and update the test that asserted the negative value was kept. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
The test now asserts that `found_posts` is clamped to zero as well as `max_num_pages`, so its name should say so. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
A negative value returned by the `found_posts` filter used to be kept, and is now clamped to zero. Record the change in the filter's docblock. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
`prepare_links()` now receives the post object, and `wp_get_latest_revision_id_and_total_count()` accepts one, so pass it through rather than its ID, which the helper would look up again. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
The result of the `found_posts_query` query is clamped to zero before it is passed to the `found_posts` filter, but only the filter's own clamp was tested. Add a test where `found_posts_query` returns a negative number, asserting that the filter receives zero. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
`prepare_links()` now accepts a post object as well as an ID, but a subclass that overrides it may still treat its argument as the ID it has received since 5.9.0, for example by concatenating it into a URL. Pass the ID from `prepare_item_for_response()` as before, so such an override keeps working. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
The `version-history` link of a global styles response was not tested. Assert that it points to the revisions, and that its `count` matches the number of revisions. Also assert that `prepare_links()` returns the same links for a post ID as for the post object, now that it accepts either. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
|
🤖 Comment by Claude Opus 5.5 (medium effort) A draft of an upstream PHPStan issue is below, for the bug that required declaring DetailsThe reproduction uses no WordPress code. It was confirmed on PHPStan 2.3.5, and on a phpstan-src checkout at 0b3ccbf80. No existing issue was found for it. The closest are phpstan/phpstan#14879 (unsealed shapes in a union lose a discriminated union) and phpstan/phpstan#7759 (a shape in a union with a general array is over-generalized). A playground link should be generated from the snippet before posting. **Title:** Union of an unsealed array shape and a list of it loses the unsealed keys
### Bug report
When an unsealed array shape is in a union with a list of the same shape, the union is merged into a general array whose key type contains only the declared keys and `int`. The unsealed `...<string, mixed>` part is lost, so an array with an extra string key, which the shape accepts on its own, is rejected by the union.
This comes up in WordPress core, where `WP_REST_Response::add_links()` takes `array<non-falsy-string, Link_Input|list<Link_Input>>`, because each link relation can map to one link or a list of links, and `Link_Input` is `array{ href: non-falsy-string, embeddable?: bool, ...<string, mixed> }`. Any link attribute that is not declared in the shape, such as `count`, is rejected as soon as a caller passes a precise shape.
### Code snippet that reproduces the problem
```php
<?php declare(strict_types = 1);
/**
* @phpstan-type Link array{ href: non-empty-string, ...<string, mixed> }
*/
class Response {
/** @param array<string, Link> $links */
public function single( array $links ): void {}
/** @param array<string, Link|list<Link>> $links */
public function single_or_list( array $links ): void {}
}
/**
* @param array{ self: array{ href: non-empty-string, count: int } } $links
*/
function test( Response $response, array $links ): void {
$response->single( $links ); // OK.
$response->single_or_list( $links ); // Error: 'count' is rejected.
}
/**
* @param array{ href: non-empty-string, ...<string, mixed> } $link
* @param array{ href: non-empty-string, ...<string, mixed> }|list<array{ href: non-empty-string, ...<string, mixed> }> $link_or_list
*/
function dump( array $link, array $link_or_list ): void {
\PHPStan\dumpType( $link );
\PHPStan\dumpType( $link_or_list );
}
```
Output at level 10:
```
19: Parameter #1 $links of method Response::single_or_list() expects array<string, array<'href'|int<0, max>, array{href: non-empty-string, ...<string, mixed>}|non-empty-string>>, array{self: array{href: non-empty-string, count: int}} given.
27: Dumped type: array{href: non-empty-string, ...<string, mixed>}
28: Dumped type: array<'href'|int<0, max>, array{href: non-empty-string, ...<string, mixed>}|non-empty-string>
```
### Expected output
No error on line 19: `array{href: non-empty-string, count: int}` is accepted by `Link` on its own, so it should also be accepted by `Link|list<Link>`.
If the union has to be generalized, the result should keep the unsealed part, e.g. a key type of `string|int<0, max>` and a value type that includes `mixed`, rather than narrowing the keys to only those that are declared.
This seems related to #14879, where two unsealed shapes in a union are merged and lose a discriminated union, and to #7759. |
There was a problem hiding this comment.
Tested locally in the Docker env: WP_REST_Global_Styles_Controller_Test and Tests_Query_NoFoundRows pass (81 tests, 281 assertions). LGTM, just a couple of small notes inline.
The found_posts clamp reverses what r65281 kept. Since that hasn't shipped yet, this seems fine, but it may be worth a short note on the Trac ticket.
AI Review: Claude Opus 5.5
| * } | ||
| */ | ||
| protected function prepare_links( $id ) { | ||
| protected function prepare_links( $post ) { |
There was a problem hiding this comment.
Nit: prepare_item_for_response() still calls this with $post->ID (line 362), which makes sense for subclasses that override prepare_links() and expect an ID. Could we add a short comment at that call site saying it's on purpose? Otherwise someone may "simplify" it to $post later.
| $found_posts_query = apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ); | ||
|
|
||
| $this->found_posts = (int) $wpdb->get_var( $found_posts_query ); | ||
| $this->found_posts = max( 0, (int) $wpdb->get_var( $found_posts_query ) ); |
There was a problem hiding this comment.
This also changes what found_posts filter callbacks receive when found_posts_query returns a negative number: they now get 0. Unlikely in practice, but maybe the @since 7.2.0 note on the filter could mention this too, not just the clamped return value?
|
Tested The |
Add a comment at the call site in `prepare_item_for_response()` saying the ID is passed on purpose, so that it isn't later "simplified" to pass the post object, which would break subclasses that override `prepare_links()` and expect an ID. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
…ount Extend the `@since 7.2.0` note on the `found_posts` filter: besides its return value being clamped, the value passed to it is now zero when the `found_posts_query` query returns a negative count. Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
…phpstan Co-Authored-By: Claude Opus 5.5 (medium effort) <noreply@anthropic.com> Claude-Code-Session-Id: 9bb536c7-7399-4262-80ed-cebfc277b43b
I only recently added that assertion 4 days ago in r65281 to test the precondition. So it's not a long-standing expected behavior. So I think the |
The `WP_REST_Global_Styles_Controller::prepare_links()` override took a post ID while the parent method takes a `WP_Post`, which PHPStan reports as an incompatible child parameter type. It now accepts either, and `prepare_item_for_response()` continues to pass the ID so that subclasses overriding the method and expecting an ID are not broken. The method also gains a precise return type, which in turn required narrowing the types it relies on: REST URLs are documented as non-empty, and `count` is declared as a non-negative link attribute. The `WP_Query::$found_posts` count is now clamped to zero, both from the `found_posts_query` query and after the `found_posts` filter, since a negative post count has no valid meaning and would otherwise surface as a negative revisions count. In r65281 only `$max_num_pages` was clamped, and its test asserted a negative `found_posts` merely as a precondition. Developed in #15826. Follow-up to r48328, r52051, r56082, r65281. Props westonruter, huzaifaalmesbah, dpknauss. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65369 602fd350-edb4-49c9-b593-d223f7449a82
The `WP_REST_Global_Styles_Controller::prepare_links()` override took a post ID while the parent method takes a `WP_Post`, which PHPStan reports as an incompatible child parameter type. It now accepts either, and `prepare_item_for_response()` continues to pass the ID so that subclasses overriding the method and expecting an ID are not broken. The method also gains a precise return type, which in turn required narrowing the types it relies on: REST URLs are documented as non-empty, and `count` is declared as a non-negative link attribute. The `WP_Query::$found_posts` count is now clamped to zero, both from the `found_posts_query` query and after the `found_posts` filter, since a negative post count has no valid meaning and would otherwise surface as a negative revisions count. In r65281 only `$max_num_pages` was clamped, and its test asserted a negative `found_posts` merely as a precondition. Developed in WordPress/wordpress-develop#15826. Follow-up to r48328, r52051, r56082, r65281. Props westonruter, huzaifaalmesbah, dpknauss. See #65817. Built from https://develop.svn.wordpress.org/trunk@65369 git-svn-id: http://core.svn.wordpress.org/trunk@64508 1a063a9b-81f0-0310-95a4-ce76da25c4cd
The `WP_REST_Global_Styles_Controller::prepare_links()` override took a post ID while the parent method takes a `WP_Post`, which PHPStan reports as an incompatible child parameter type. It now accepts either, and `prepare_item_for_response()` continues to pass the ID so that subclasses overriding the method and expecting an ID are not broken. The method also gains a precise return type, which in turn required narrowing the types it relies on: REST URLs are documented as non-empty, and `count` is declared as a non-negative link attribute. The `WP_Query::$found_posts` count is now clamped to zero, both from the `found_posts_query` query and after the `found_posts` filter, since a negative post count has no valid meaning and would otherwise surface as a negative revisions count. In r65281 only `$max_num_pages` was clamped, and its test asserted a negative `found_posts` merely as a precondition. Developed in WordPress#15826. Follow-up to r48328, r52051, r56082, r65281. Props westonruter, huzaifaalmesbah, dpknauss. See #65817. git-svn-id: https://develop.svn.wordpress.org/trunk@65369 602fd350-edb4-49c9-b593-d223f7449a82

✅ Committed in r65369 (49121d7).
Makes
WP_REST_Global_Styles_Controller::prepare_links()accept a post object, matching the parent method, and gives it a precise return type. This removes the corresponding entry from themethod.childParameterTypePHPStan baseline, and syncs the change from WordPress/gutenberg#86470.Global styles controller
WP_REST_Global_Styles_ControllerextendsWP_REST_Posts_Controller, whoseprepare_links( $post )takes aWP_Post. The override took a post ID instead, which PHPStan reports as an incompatible child parameter type. It now takesWP_Post|int $post, so it accepts what the parent method does while any caller that passes an ID keeps working.prepare_item_for_response()still passes the ID, so a subclass that overridesprepare_links()and treats its argument as an ID is not broken.selfandabout, plusversion-historywith its revisionscountwhen the post type supports revisions.Types that the return type relies on
get_rest_url()andrest_url()returnnon-falsy-string. The URL is always the home URL followed by the REST prefix and a route starting with/, or byindex.phpwith arest_routequery arg. Therest_urlfilter's$urlis documented asnon-falsy-stringtoo, so the filtered value is typed by the same contract. This lets REST URLs be used as linkhrefs, whichWP_REST_Response::add_links()requires to be non-empty.WP_Query::$found_postsisint<0, max>, and so is thefound_postsfilter's$found_posts. This follows r65281 (Code Quality: Fix thenullCoalesce.propertyPHPStan error and remove the baseline #15475), which documented$max_num_pagesasint<0, max>and clamped it to zero. TheFOUND_ROWS()result and the value returned by thefound_postsfilter are both clamped to zero in the same way, since either can be filtered to a negative number.wp_get_latest_revision_id_and_total_count()returns this count, so itscountisint<0, max>as well.countis declared as anint<0, max>link attribute inWP_REST_Response'sLink_AttributesandLink_Inputtypes. Besides global styles, it is used forversion-historylinks by the posts and templates controllers. It has to be declared rather than left to the unsealed...<string, mixed>: PHPStan mergesLink_Inputwith its list form inadd_links()and drops the unsealed keys, so any attribute not named in the shape is rejected when a caller passes a precise shape. This looks like a PHPStan bug, related to Merging of array shapes in union loses discriminated unions when using unsealed shapes phpstan/phpstan#14879.Baselines
method.childParameterTypeentry.argument.type: the existingheader()errors forX-WP-Totalin three controllers now reportint<0, max>instead ofint. The number of errors is unchanged.Behavior change
A negative
found_postscount, from either a filteredfound_posts_queryor thefound_postsfilter, is now clamped to zero. r65281 kept a negative value from the filter, and asserted so in a test, while clamping only$max_num_pages. That test now asserts zero. Otherwise there is no change in behavior.Tests
found_posts_queryclamp is covered by a new test inTests_Query_NoFoundRows.version-historylink was not tested. New tests assert itshrefand that itscountmatches the number of revisions, and thatprepare_links()returns the same links for a post ID as for the post object.WP_REST_Global_Styles_Controller_Test,WP_REST_Global_Styles_Revisions_Controller_Test,WP_Test_REST_Revisions_Controller,WP_Test_REST_Posts_Controller,Tests_Post_Revisions,Tests_Post_Query, andTests_Query_NoFoundRowstests pass.Trac ticket: https://core.trac.wordpress.org/ticket/65817
Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5 (medium effort)
Used for: Investigating the PHPStan errors, probing the types, drafting the changes, and syncing them between Gutenberg and Core; reviewed and directed by me.
This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.