Skip to content

Commit 0ac67da

Browse files
Abilities API: Encode empty object results as JSON objects.
The run endpoint prepared only associative array results for JSON clients, so an empty array returned for an object output schema, such as the `core/settings-get` result when no setting matches, was encoded as [] and failed output validation in JSON clients. Prepare every result, including root results, lists and object results, so empty objects are encoded as {} while arrays stay arrays. Register the run endpoint with the `data_processing` route option set to `false`, so the `_fields` and `_embed` parameters and response links leave the result unchanged and it follows the ability's output schema whether it is an object, an array, or a scalar value. The REST API client fixture lists the disabled processing for the run endpoint. Follow-up to [64311], [64592], [64689]. See #66267.
1 parent 390a294 commit 0ac67da

4 files changed

Lines changed: 220 additions & 26 deletions

File tree

‎src/wp-includes/rest-api/endpoints/class-wp-rest-abilities-v1-run-controller.php‎

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,13 @@ public function register_routes(): void {
6565
'callback' => array( $this, 'execute_ability' ),
6666
'permission_callback' => array( $this, 'check_ability_permissions' ),
6767
'args' => $this->get_run_args(),
68+
69+
/*
70+
* Serve the ability result as returned, so it follows the ability's output
71+
* schema whether it is an object, an array, or a scalar value: `_fields`,
72+
* `_embed` and response links leave it unchanged.
73+
*/
74+
'data_processing' => false,
6875
),
6976
'schema' => array( $this, 'get_run_schema' ),
7077
)
@@ -96,18 +103,10 @@ public function execute_ability( $request ) {
96103
}
97104

98105
/*
99-
* Preserve empty objects in nested properties when encoding an associative
100-
* result as JSON. Preparation can convert empty PHP arrays to stdClass.
101-
*
102-
* The REST server's `_fields` and `_embed` processing expects arrays at the
103-
* response root and for numeric collection items. Converting those values
104-
* to objects would cause type errors, so skip root empty arrays and numeric
105-
* collections until that processing supports objects. An empty object result
106-
* therefore still encodes as [], and a list containing one encodes as [[]].
106+
* Preserve empty objects when encoding the result as JSON. Preparation can
107+
* convert empty PHP arrays to stdClass, also within object results.
107108
*/
108-
if ( is_array( $result ) && ! wp_is_numeric_array( $result ) ) {
109-
$result = wp_prepare_json_value_for_client( $result, $ability->get_output_schema() );
110-
}
109+
$result = wp_prepare_json_value_for_client( $result, $ability->get_output_schema() );
111110

112111
return rest_ensure_response( $result );
113112
}

‎tests/phpunit/tests/rest-api/wpRestAbilitiesSettingsController.php‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,50 @@ public function test_fields_filter_from_query_string_limits_settings(): void {
196196
$this->assertEqualSets( array( 'title', 'posts_per_page' ), array_keys( $data ), 'Only the settings from the comma-separated list should be returned.' );
197197
}
198198

199+
/**
200+
* Data provider for test_no_matching_setting_is_encoded_as_an_empty_object().
201+
*
202+
* @return array<string, array{0: array<string, string>}>
203+
*/
204+
public static function data_global_params(): array {
205+
return array(
206+
'no global parameter' => array( array() ),
207+
'_fields' => array( array( '_fields' => 'title' ) ),
208+
'_embed' => array( array( '_embed' => '1' ) ),
209+
);
210+
}
211+
212+
/**
213+
* An empty result is encoded as a JSON object, which the output schema requires,
214+
* also when the global `_fields` or `_embed` parameter is given.
215+
*
216+
* @ticket 66267
217+
* @dataProvider data_global_params
218+
*
219+
* @param array<string, string> $global_params The global parameters sent with the request.
220+
*/
221+
public function test_no_matching_setting_is_encoded_as_an_empty_object( array $global_params ): void {
222+
$request = $this->run_request(
223+
array(
224+
'group' => 'reading',
225+
'fields' => 'title',
226+
)
227+
);
228+
foreach ( $global_params as $name => $value ) {
229+
$request->set_param( $name, $value );
230+
}
231+
232+
$response = $this->server->dispatch( $request );
233+
234+
$this->assertSame( 200, $response->get_status(), 'Filters that match no setting should be accepted.' );
235+
236+
add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
237+
$response = apply_filters( 'rest_post_dispatch', $response, $this->server, $request );
238+
$data = $this->server->response_to_data( $response, isset( $global_params['_embed'] ) );
239+
240+
$this->assertSame( '{}', wp_json_encode( $data ), 'The empty result should be encoded as an empty object.' );
241+
}
242+
199243
/**
200244
* @ticket 64605
201245
*/

‎tests/phpunit/tests/rest-api/wpRestAbilitiesV1RunController.php‎

Lines changed: 161 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,118 @@ private function register_test_abilities(): void {
443443
)
444444
);
445445

446+
// Ability that returns an object result with an empty object property.
447+
$this->register_test_ability(
448+
'test/nested-empty-object-in-object-output',
449+
array(
450+
'label' => 'Nested Empty Object In Object Output',
451+
'description' => 'Returns an object result with an empty object property.',
452+
'category' => 'general',
453+
'output_schema' => array(
454+
'type' => 'object',
455+
'properties' => array(
456+
'settings' => array( 'type' => 'object' ),
457+
),
458+
),
459+
'execute_callback' => static function () {
460+
return (object) array( 'settings' => array() );
461+
},
462+
'permission_callback' => '__return_true',
463+
'meta' => array(
464+
'show_in_rest' => true,
465+
),
466+
)
467+
);
468+
469+
// Ability that returns a JsonSerializable result with an empty object property.
470+
$this->register_test_ability(
471+
'test/nested-empty-object-in-json-serializable-output',
472+
array(
473+
'label' => 'Nested Empty Object In JsonSerializable Output',
474+
'description' => 'Returns a JsonSerializable result with an empty object property.',
475+
'category' => 'general',
476+
'output_schema' => array(
477+
'type' => 'object',
478+
'properties' => array(
479+
'settings' => array( 'type' => 'object' ),
480+
),
481+
),
482+
'execute_callback' => static function () {
483+
return new class() implements JsonSerializable {
484+
public function jsonSerialize(): array {
485+
return array( 'settings' => array() );
486+
}
487+
};
488+
},
489+
'permission_callback' => '__return_true',
490+
'meta' => array(
491+
'show_in_rest' => true,
492+
),
493+
)
494+
);
495+
496+
// Ability that returns an empty list.
497+
$this->register_test_ability(
498+
'test/empty-list-output',
499+
array(
500+
'label' => 'Empty List Output',
501+
'description' => 'Returns an empty list.',
502+
'category' => 'general',
503+
'output_schema' => array(
504+
'type' => 'array',
505+
'items' => array( 'type' => 'object' ),
506+
),
507+
'execute_callback' => static function () {
508+
return array();
509+
},
510+
'permission_callback' => '__return_true',
511+
'meta' => array(
512+
'show_in_rest' => true,
513+
),
514+
)
515+
);
516+
517+
// Ability that returns a list of strings.
518+
$this->register_test_ability(
519+
'test/string-list-output',
520+
array(
521+
'label' => 'String List Output',
522+
'description' => 'Returns a list of strings.',
523+
'category' => 'general',
524+
'output_schema' => array(
525+
'type' => 'array',
526+
'items' => array( 'type' => 'string' ),
527+
),
528+
'execute_callback' => static function () {
529+
return array( 'a', 'b' );
530+
},
531+
'permission_callback' => '__return_true',
532+
'meta' => array(
533+
'show_in_rest' => true,
534+
),
535+
)
536+
);
537+
538+
// Ability that returns a string.
539+
$this->register_test_ability(
540+
'test/string-output',
541+
array(
542+
'label' => 'String Output',
543+
'description' => 'Returns a string.',
544+
'category' => 'general',
545+
'output_schema' => array(
546+
'type' => 'string',
547+
),
548+
'execute_callback' => static function () {
549+
return 'value';
550+
},
551+
'permission_callback' => '__return_true',
552+
'meta' => array(
553+
'show_in_rest' => true,
554+
),
555+
)
556+
);
557+
446558
// Read-only ability for query params testing.
447559
$this->register_test_ability(
448560
'test/query-params',
@@ -633,39 +745,73 @@ public function test_output_validation(): void {
633745
/**
634746
* Data provider for test_output_is_prepared_for_json_clients().
635747
*
636-
* @return array<string, array{0: string, 1: string}>
748+
* Each result is requested without global parameters, with `_fields` and `_embed`,
749+
* and with a link that a `rest_post_dispatch` filter adds, alone and embedded.
750+
*
751+
* @return array<string, array{0: string, 1: string, 2: string}>
637752
*/
638753
public static function data_output_is_prepared_for_json_clients(): array {
639-
return array(
640-
'root empty object stays unchanged' => array( 'test/empty-object-output', '[]' ),
641-
'nested empty object' => array( 'test/nested-empty-object-output', '{"settings":{}}' ),
642-
'numeric collection stays unchanged' => array( 'test/empty-object-list-output', '[[]]' ),
643-
);
754+
$results = array(
755+
'root empty object' => array( 'test/empty-object-output', '{}' ),
756+
'nested empty object' => array( 'test/nested-empty-object-output', '{"settings":{}}' ),
757+
'numeric collection' => array( 'test/empty-object-list-output', '[{}]' ),
758+
'object result' => array( 'test/nested-empty-object-in-object-output', '{"settings":{}}' ),
759+
'JsonSerializable result' => array( 'test/nested-empty-object-in-json-serializable-output', '{"settings":{}}' ),
760+
'root empty list' => array( 'test/empty-list-output', '[]' ),
761+
'list of strings' => array( 'test/string-list-output', '["a","b"]' ),
762+
'string' => array( 'test/string-output', '"value"' ),
763+
);
764+
765+
$data = array();
766+
foreach ( $results as $label => $result ) {
767+
foreach ( array( 'none', '_fields', '_embed', 'link', 'embedded link' ) as $global_param ) {
768+
$data[ "{$label}, {$global_param}" ] = array( $result[0], $global_param, $result[1] );
769+
}
770+
}
771+
772+
return $data;
644773
}
645774

646775
/**
647-
* Tests that ability results are prepared for JSON clients without breaking
648-
* the global `_fields` and `_embed` parameters.
776+
* Tests that ability results are prepared for JSON clients, and that the global
777+
* `_fields` and `_embed` parameters and response links leave them unchanged.
649778
*
650779
* @ticket 66267
651780
* @dataProvider data_output_is_prepared_for_json_clients
652781
*
653782
* @param string $ability_name The ability name.
783+
* @param string $global_param The global parameter sent with the request, 'link' or
784+
* 'embedded link' for a link added by a filter, or 'none'.
654785
* @param string $expected The expected encoded result.
655786
*/
656-
public function test_output_is_prepared_for_json_clients( string $ability_name, string $expected ): void {
657-
$request = new WP_REST_Request( 'POST', "/wp-abilities/v1/abilities/{$ability_name}/run" );
658-
$response = $this->server->dispatch( $request );
787+
public function test_output_is_prepared_for_json_clients( string $ability_name, string $global_param, string $expected ): void {
788+
$request = new WP_REST_Request( 'POST', "/wp-abilities/v1/abilities/{$ability_name}/run" );
789+
if ( '_fields' === $global_param ) {
790+
// No result has this field, so filtering would leave none of the result.
791+
$request->set_param( '_fields', 'other' );
792+
} elseif ( '_embed' === $global_param || 'embedded link' === $global_param ) {
793+
$request->set_param( '_embed', '1' );
794+
}
659795

660-
$this->assertSame( 200, $response->get_status() );
661-
$this->assertSame( $expected, wp_json_encode( $response->get_data() ) );
796+
if ( 'link' === $global_param || 'embedded link' === $global_param ) {
797+
add_filter(
798+
'rest_post_dispatch',
799+
static function ( $response ) {
800+
$response->add_link( 'alternate', rest_url( '/wp-abilities/v1/abilities' ), array( 'embeddable' => true ) );
801+
return $response;
802+
}
803+
);
804+
}
805+
806+
$response = $this->server->dispatch( $request );
662807

663-
$request->set_param( '_fields', 'settings' );
808+
$this->assertSame( 200, $response->get_status(), 'The ability should run successfully.' );
664809

665810
add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
666811
$response = apply_filters( 'rest_post_dispatch', $response, $this->server, $request );
812+
$data = $this->server->response_to_data( $response, $request->has_param( '_embed' ) );
667813

668-
$this->assertSame( $expected, wp_json_encode( $this->server->response_to_data( $response, true ) ) );
814+
$this->assertSame( $expected, wp_json_encode( $data ), 'The result should be encoded as expected.' );
669815
}
670816

671817
/**

‎tests/qunit/fixtures/wp-api-generated.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12682,6 +12682,11 @@ mockedApiResponse.Schema = {
1268212682
"PATCH",
1268312683
"DELETE"
1268412684
],
12685+
"data_processing": {
12686+
"fields": false,
12687+
"embed": false,
12688+
"links": false
12689+
},
1268512690
"args": {
1268612691
"name": {
1268712692
"description": "Unique identifier for the ability.",

0 commit comments

Comments
 (0)