Opened 6 weeks ago
Last modified 3 weeks ago
#66230 new defect (bug)
REST API: rest_filter_response_fields() fatals on PHP 8 when response data is stdClass (e.g. /wp/v2/taxonomies?type=…&_fields=…)
| Reported by: | eeeeeeeeeeeee | Owned by: | |
|---|---|---|---|
| Priority: | normal | Milestone: | Awaiting Review |
| Component: | REST API | Version: | |
| Severity: | normal | Keywords: | has-patch has-unit-tests |
| Cc: | Focuses: |
Description (last modified by )
On PHP 8+, requesting a taxonomy collection with _fields can fatal instead of returning a trimmed JSON response.
rest_filter_response_fields() passes response data into _rest_array_intersect_key_recursive(), which calls array_intersect_key() without ensuring the value is an array. When WP_REST_Response::get_data() is a stdClass (seen with /wp/v2/taxonomies?type={post_type}&_fields=…), PHP throws:
TypeError: array_intersect_key(): Argument #1 ($array) must be of type array, stdClass given
in wp-includes/rest-api.php (_rest_array_intersect_key_recursive)
Related: for slug-keyed collections such as /wp/v2/taxonomies and /wp/v2/types, _fields intersects top-level keys (taxonomy/type slugs) with field names (name, slug, …), so a successful response is often an empty array [] even when taxonomies exist. Filtering should be applied per item in the collection.
Steps to reproduce
Site on PHP 8.0+ with at least one public custom post type that has a REST-visible taxonomy (e.g. CPT UI testimonial + testimonial_category), or any setup that yields object-shaped taxonomy collection data for a type filter.
While logged in (or with sufficient caps), open or request:
GET /wp-json/wp/v2/taxonomies?type=testimonial&_fields=name,slug,rest_base,hierarchical,types
(Substitute any post type slug that has associated taxonomies.)
Observe HTTP 500 and the TypeError above in the error log.
Also compare:
GET /wp-json/wp/v2/taxonomies
GET /wp-json/wp/v2/taxonomies?_fields=name,slug,types,rest_base
The second often returns [] even though the first returns a non-empty object keyed by taxonomy slug.
Expected behavior
No fatal.
_fields returns a trimmed representation of each taxonomy in the collection.
Non-array response data is coerced to an array (or skipped) before array_intersect_key().
Actual behavior
Uncaught TypeError in _rest_array_intersect_key_recursive() when data is stdClass.
Environment
WordPress 6.x / 7.x (reproduced with current rest_filter_response_fields / _rest_array_intersect_key_recursive)
PHP 8.x (strict types on array_intersect_key())
Triggered from the block editor / CPT UI (User-Agent: node) hitting the taxonomies endpoint after editing a CPT
Code pointer
wp-includes/rest-api.php:
rest_filter_response_fields()
_rest_array_intersect_key_recursive() — assumes $array1 is always an array
rest_api_default_filters() re-registers rest_filter_response_fields on rest_api_init.
Suggested fix
Guard/coerce in _rest_array_intersect_key_recursive() / rest_filter_response_fields():
<?php if ( is_object( $data ) ) { $data = get_object_vars( $data ); // or recursive array cast } if ( ! is_array( $data ) ) { return $response; }
For non-numeric collections whose values are arrays/objects and whose keys are not in the _fields list, apply _rest_array_intersect_key_recursive() to each item (same idea as the wp_is_numeric_array() branch).
Change History (11)
This ticket was mentioned in PR #13929 on WordPress/wordpress-develop by @mitgiselle.
6 weeks ago
#1
- Keywords has-patch has-unit-tests added
This ticket was mentioned in PR #13931 on WordPress/wordpress-develop by @abditsori.
6 weeks ago
#2
Fixes: https://core.trac.wordpress.org/ticket/66230
Summary
_rest_array_intersect_key_recursive()calledarray_intersect_key()without verifying its argument was an array, which fatals on PHP 8 whenWP_REST_Response::get_data()returns astdClass(e.g. an empty collection a controller casts to an object so it's encoded as{}instead of[], as seen on/wp/v2/taxonomies?type=...&_fields=...when the type has no visible taxonomies).- Collections keyed by a non-numeric identifier (e.g.
/wp/v2/taxonomiesand/wp/v2/types, keyed by slug) had_fieldsintersected against the collection's own top-level slug keys instead of against each item's fields, so a successful request often returned an empty result ([]) even when items existed. rest_filter_response_fields()now coerces object data to an array (and back, to preserve the{}vs[]JSON shape), and_rest_array_intersect_key_recursive()guards against non-array input. A new_rest_is_keyed_collection()helper detects slug-keyed collections so_fieldsis applied per item.
Test plan
- [x] Added
Tests_REST_API::test_rest_filter_response_fields_empty_object_dataand::test_rest_filter_response_fields_keyed_collectioncovering the fixed behavior directly. - [x] Added
WP_Test_REST_Taxonomies_Controller::test_get_taxonomies_for_type_with_fields_does_not_fataland::test_get_taxonomies_for_invalid_type_with_fields_does_not_fatalreproducing the original/wp/v2/taxonomies?type=...&_fields=...crash end-to-end. - [x] Full relevant PHPUnit coverage passes locally:
Tests_REST_API(265 tests),WP_Test_REST_Taxonomies_Controller(35 tests),WP_Test_REST_Post_Types_Controller(26 tests, same code path for/wp/v2/types). - [x]
phpcs/WPCS clean on all changed files.
🤖 Generated with Claude Code
#4
@
6 weeks ago
### Test & Review Report
Ticket: https://core.trac.wordpress.org/ticket/66230
PR #13929: https://github.com/WordPress/wordpress-develop/pull/13929 (by @guzel)
PR #13931: https://github.com/WordPress/wordpress-develop/pull/13931 (by @AbdiTolesa)
---
#### Environment
- WordPress: 7.2-alpha-63166-src (trunk)
- PHP: 8.3.33
- Server: macOS Darwin 24.6.0 (arm64)
- Database: MariaDB 10.11 / MySQL
- PHPUnit: 9.6.37
- PHPCS: 3.13.5 (WordPress-Core)
---
#### Steps to Reproduce on trunk (Before Patch)
- In PHP 8.0+, dispatch a REST request to
/wp/v2/taxonomiesquerying an invalid or empty post type with_fieldsrequested:`php $request = new WP_REST_Request( 'GET', '/wp/v2/taxonomies' ); $request->set_param( 'type', 'wingding' ); $request->set_param( '_fields', 'name,slug' ); $server = rest_get_server(); $response = $server->dispatch( $request ); add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 ); $response = apply_filters( 'rest_post_dispatch', $response, $server, $request );` - Observe fatal
TypeError:` Fatal error: Uncaught TypeError: array_intersect_key(): Argument #1 ($array) must be of type array, stdClass given in src/wp-includes/rest-api.php:932 Stack trace: #0 src/wp-includes/rest-api.php(932): array_intersect_key(Object(stdClass), Array) #1 src/wp-includes/rest-api.php(991): _rest_array_intersect_key_recursive(Object(stdClass), Array) #2 rest_filter_response_fields(...)`
Root Cause:
WP_REST_Taxonomies_Controller::get_items() casts empty collection arrays to (object) $data so that json encoding returns {} rather than []. In rest_filter_response_fields(), the response data is forwarded directly to _rest_array_intersect_key_recursive(), which invokes PHP's native array_intersect_key(). In PHP 8.0+, passing non-array types (such as stdClass, null, or scalars) triggers a fatal TypeError.
---
#### Evaluation of PR #13929 (@guzel)
Implementation:
In rest_filter_response_fields(), checks if ( is_object( $data ) ) { return $response; }.
Test Results:
- Fatal Error Resolved: Dispatching
/wp/v2/taxonomies?type=wingding&_fields=name,slugreturns HTTP 200 with{}as expected. - PHPUnit:
vendor/bin/phpunit --filter WP_Test_REST_Taxonomies_Controllerpasses (34 tests, 158 assertions, including the newtest_get_taxonomies_for_invalid_type_with_fields).vendor/bin/phpunit --filter Tests_REST_APIpasses (405 tests, 846 assertions).
- PHPCS:
vendor/bin/phpcs src/wp-includes/rest-api.php tests/phpunit/tests/rest-api/rest-taxonomies-controller.phppasses with 0 errors and 0 warnings.
- Backward Compatibility: 100% backward compatible; existing slug filtering syntax (
?_fields=categoryor?_fields=category.name) continues to function without disturbance. - Minor Note / Potential Hardening: Core could consider checking
if ( ! is_array( $data ) ) { return $response; }to defensively guard against any endpoint returningnullor scalars alongside objects, or guard_rest_array_intersect_key_recursive()withif ( ! is_array( $array1 ) || ! is_array( $array2 ) ) { return array(); }.
---
#### Evaluation of PR #13931 (@AbdiTolesa)
Implementation:
Casts $data to (array) and back to (object), adds a new _rest_is_keyed_collection() helper, and filters per item on slug-keyed collections.
Findings & Architectural Concerns:
- Fragile Heuristic in
_rest_is_keyed_collection():- The helper checks:
`php if ( isset( $fields_as_keyed[ $key ] ) ) {
- The helper checks:
return false;
}
`
If a site registers a custom taxonomy or post type whose slug matches any requested field name (e.g., a taxonomy with slug'name','slug','type', or'description'),isset( $fields_as_keyed[ $key ] )evaluates totrue. This causes_rest_is_keyed_collection()to returnfalse, breaking per-item filtering unexpectedly.
- False Positives on Single Resource Endpoints:
- Any single-item endpoint whose top-level properties are all arrays/objects (e.g., grouped site settings, theme palettes, site health debug info) is misidentified as a "collection" whenever requested fields do not match top-level section keys.
- Out of Scope / Compatibility Shift for Slug-Keyed Endpoints:
- In WordPress REST API,
/wp/v2/taxonomiesand/wp/v2/typesreturn schema maps keyed by slug. Existing clients rely on_fields=categoryor dot syntax_fields=category.name. Changing this behavior is a broader design decision that deserves a dedicated enhancement ticket rather than being bundled with this bugfix.
- In WordPress REST API,
- Incorrect DocBlock Annotations:
- All 4 test methods introduced in PR #13931 reference
@ticket 62534instead of@ticket 66230.
- All 4 test methods introduced in PR #13931 reference
---
#### Recommendation
Recommend proceeding with PR #13929 (with the optional hardening to ! is_array( $data )). It cleanly resolves the PHP 8 fatal error with zero risk of regressions or unexpected side effects on existing REST consumers.
Props therssoftware.
---
AI Disclosure: In accordance with the WordPress AI policy, I disclose that generative AI (Google Antigravity) was used in testing and drafting this test report. All test steps, code evaluations, and PHPUnit/PHPCS executions were performed and verified in the local development environment.
#5
@
6 weeks ago
- Description modified (diff)
@eeeeeeeeeeeee Thanks for opening a ticket. Please try to format the description with Trac's WikiFormatting for future tickets. I did a bit of tidying to improve readability.
#6
@
6 weeks ago
@abditsori @therssoftware I see you've both opened PRs. Please discuss with each other on the merits of either of your approaches.
#7
@
6 weeks ago
Thanks @westonruter!
Looking at both PRs, they are tackling two distinct aspects:
- The PHP 8 fatal error (Ticket #66230):
When
/wp/v2/taxonomiesreturns an empty collection, it is cast tostdClassso it serializes as{}instead of[]. PassingstdClasstoarray_intersect_key()triggers an uncaughtTypeErrorin PHP 8+.- PR #13929 addresses this directly and surgically: if
$datais an object (empty collection), it returns$responseunchanged because there are no fields to filter. We can also defensively guard_rest_array_intersect_key_recursive()withif ( ! is_array( $array1 ) || ! is_array( $array2 ) ) { return array(); }. - This has zero risk of regressions or side-effects for existing REST consumers.
- PR #13929 addresses this directly and surgically: if
- Per-item filtering on slug-keyed collections (PR #13931):
PR #13931 also attempts to change how
_fieldsbehaves for non-empty slug-keyed collections (/wp/v2/taxonomiesand/wp/v2/types) via a new helper_rest_is_keyed_collection(). While the intent is understandable, there are a few architectural considerations:- Slug name collision: The helper checks
if ( isset( $fields_as_keyed[ $key ] ) ) { return false; }. If a site registers a taxonomy or CPT whose slug matches a requested field name (e.g. slug'name','slug','type', or'description'), the heuristic returnsfalseand item-level filtering breaks. - False positives: Single-item responses with nested structures (like
/wp/v2/settings) could be misclassified if requested fields don't match top-level keys. - Backward compatibility & scope: Currently, clients filter slug-keyed maps using top-level slug keys (
?_fields=categoryor dot notation?_fields=category.name). Changing this is a significant behavioral shift that warrants its own enhancement ticket with schema/REST team consensus.
- Slug name collision: The helper checks
### Recommendation
I suggest we proceed with the focused fix in PR #13929 (incorporating any defensive type guards) to cleanly resolve the PHP 8 fatal bug for this ticket.
If we want to support per-item filtering for slug-keyed map collections, we can spin that off into a dedicated enhancement ticket so it can receive full architectural discussion without blocking the bug fix.
What do you think @abditsori @westonruter?
@martin.krcho commented on PR #13929:
5 weeks ago
#8
Thanks @guzel for the clear write-up and the focused fix. I tested this locally (current trunk, PHP 8, Docker env) and it fixes the fatal error from [https://core.trac.wordpress.org/ticket/66230 [#66230]](https://core.trac.wordpress.org/ticket/66230).
I suggest two small changes. With them, I think this is ready for a committer.
1. Guard against all non-array data, not only objects. @therssoftware suggested this on the ticket too.
On trunk, the same TypeError also happens when the response data is a string, a boolean, or null. A custom route can return any of these. Changing the check to ! is_array() covers all of them, and array data still goes through the same path:
// Only array data has fields to filter, e.g. an empty collection may be an object so it is encoded as `{}`. if ( ! is_array( $data ) ) { return $response; }
2. Add a unit test next to the existing test_rest_filter_response_fields_* tests, and simplify the controller test.
A data-provider test in tests/phpunit/tests/rest-api.php covers the fix directly, with no controller needed:
/** * Ensure that response data which is not an array is returned unchanged when request['_fields'] is present. * * @ticket 66230 * * @dataProvider data_rest_filter_response_fields_non_array_data * * @param mixed $data Response data. */ public function test_rest_filter_response_fields_non_array_data( $data ) { $response = new WP_REST_Response( $data ); $request = array( '_fields' => 'name,slug', ); $response = rest_filter_response_fields( $response, null, $request ); $this->assertSame( $data, $response->get_data() ); } /** * Data provider. * * @return array[] */ public static function data_rest_filter_response_fields_non_array_data() { $json_serializable = new class() implements JsonSerializable { #[ReturnTypeWillChange] public function jsonSerialize() { return array( 'name' => 'a' ); } }; return array( 'empty object' => array( new stdClass() ), 'object' => array( (object) array( 'name' => 'a' ) ), 'JsonSerializable' => array( $json_serializable ), 'string' => array( 'string' ), 'boolean' => array( true ), 'null' => array( null ), ); }
The controller test can be shorter. rest_filter_response_fields() is already hooked during tests, so add_filter()/remove_filter() are not needed. dispatch() already returns 200, so the status assertion is not needed either:
/** * @ticket 66230 */ public function test_get_taxonomies_for_invalid_type_with_fields() { $request = new WP_REST_Request( 'GET', '/wp/v2/taxonomies' ); $request->set_param( 'type', 'wingding' ); $request->set_param( '_fields', 'name,slug' ); $server = rest_get_server(); $response = rest_filter_response_fields( $server->dispatch( $request ), $server, $request ); $this->assertSame( '{}', wp_json_encode( $response->get_data() ) ); }
Results with both changes applied:
- Without the
src/change: all 7 new test cases fail with theTypeError. - With the change: all pass, and the existing
_fieldstests still pass. - The full
restapigroup: 3,576 tests, no new failures. The one error (Test_oEmbed_Controller::test_proxy_with_classic_embed_provider) and four warnings also happen on clean trunk. phpcs: clean.
I agree with keeping the slug-keyed _fields behavior out of this PR. It can be handled in a follow-up ticket, so this fatal fix can land on its own.
@martin.krcho commented on PR #13931:
5 weeks ago
#9
Thanks @AbdiTolesa for working on this, and for looking at the slug-keyed _fields problem too. That part of [https://core.trac.wordpress.org/ticket/66230 [#66230]](https://core.trac.wordpress.org/ticket/66230) is real.
To help the ticket move forward, I suggest landing the fatal-error fix on its own through [https://github.com/WordPress/wordpress-develop/pull/13929 [#13929]](https://github.com/WordPress/wordpress-develop/pull/13929). It is smaller and does not change any existing behavior. The per-item _fields change for /wp/v2/taxonomies and /wp/v2/types changes how existing responses look, so it fits better in a separate follow-up ticket. This PR could be a good starting point there.
A few notes from local testing, in case they help with that follow-up:
- The controller tests do not run the filter.
rest_get_server()->dispatch()does not applyrest_post_dispatch, sorest_filter_response_fields()is never called. Both controller tests still pass when thesrc/change is reverted. Callingrest_filter_response_fields( $response, $server, $request )after the dispatch makes them real regression tests. JsonSerializabledata is lost. Casting aJsonSerializableobject with(array)reads its internal properties, not what it serializes to. For example, an object that serializes to{"name":"n","x":1}comes back as{}with_fields=name. Returning object data unchanged avoids this._rest_is_keyed_collection()depends on the field names. For example,_fields=nameis applied per item, but_fields=name,categoryis not. A single item whose values are all arrays is also treated as a collection when none of the requested fields matches its top-level keys: it returns{"settings":[],"styles":[]}instead of[].- Wrong ticket number. The
@tickettags say62534instead of66230.
@mitgiselle commented on PR #13929:
5 weeks ago
#10
Thanks @martinkrcho for testing and for the review. I applied both suggestions.
The guard is now ! is_array( $data ), so strings, booleans and null are covered as well as objects.
I added test_rest_filter_response_fields_non_array_data with your data provider, and simplified the taxonomies controller test as suggested.
Thank you!
#11
@
3 weeks ago
The fatal appears to be fixed on trunk by [64689] (#66372), which added the same ! is_array( $data ) guard to rest_filter_response_fields() that was agreed for PR #13929. PR #13929's tests pass on unpatched trunk, and fail if that guard is removed. The PR's tests could still be worth committing as regression coverage. The per-item _fields behaviour for slug-keyed collections (/wp/v2/taxonomies, /wp/v2/types) remains open and fits a separate enhancement ticket, as discussed above.
Problem
On PHP 8, requesting a taxonomy collection with
_fieldscan fatal instead of returning a response:Cause
WP_REST_Taxonomies_Controller::get_items()returns an emptystdClasswhen no taxonomy matches, so that an empty collection is serialized as a JSON object ({}) rather than an array ([]).rest_filter_response_fields()then passes that data to_rest_array_intersect_key_recursive(), which callsarray_intersect_key()and requires an array.Note: the ticket describes the failure for a post type that has taxonomies. On trunk I could only reproduce it when the collection is empty (no REST-visible taxonomies for the requested
type, or none the user can assign).Fix
Return the response unchanged when its data is an object. There are no fields to filter, and the empty collection is still serialized as
{}. The function's signature and return type are unchanged, and array data follows the same path as before.Out of scope
For non-empty slug-keyed collections such as
/wp/v2/taxonomiesand/wp/v2/types,_fieldsis applied to the top-level slug keys, so?_fields=name,slugreturns[]. That is existing behavior (?_fields=category.nameworks today), and changing it would be a compatibility decision, so I left it for a separate discussion.Testing instructions
/wp-json/wp/v2/taxonomies?type=wingding&_fields=name,slug(any post type with no REST-visible taxonomies works).Before: HTTP 500 and the
TypeErrorabove.After: HTTP 200 with
{}.Automated tests
WP_Test_REST_Taxonomies_Controller::test_get_taxonomies_for_invalid_type_with_fieldsasserts a 200 status and a{}body.It fails before the change with the
TypeErrorabove and passes after. Therestapigroup was run locally (3570 tests); the only error isTest_oEmbed_Controller::test_proxy_with_classic_embed_provider, which fails identically without this change.AI assistance
The test was written first and confirmed failing against unpatched trunk, then confirmed passing after the change. All output was reviewed by me before submission.
🤖 Generated with Claude Code