8000 Return empty taxonomy collections as JSON object, not array · WP-API/WP-API@185608f · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on Sep 24, 2018. It is now read-only.

Commit 185608f

Browse files
committed
Return empty taxonomy collections as JSON object, not array
The response from `/wp/v2/taxonomies` is a JSON object, keyed with the name of each taxonomy. If you use the `?type=` query parameter to specify an object for which no taxonomies are available, or to specify an invalid type of object, the empty PHP `array()` will be rendered in JSON as `[]`. To ensure that the type of this resource's response remains consistent this pull request casts empty arrays to a PHP object, which will be correctly rendered as `{}` in the response JSON. Fixes #2803
1 parent fe4a14a commit 185608f

File tree

2 files changed

+16
-1
lines changed

2 fil 10000 es changed

+16
-1
lines changed

lib/endpoints/class-wp-rest-taxonomies-controller.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,12 @@ public function get_items( $request ) {
8383
$tax = $this->prepare_response_for_collection( $tax );
8484
$data[ $tax_type ] = $tax;
8585
}
86+
87+
if ( empty( $data ) ) {
88+
// Response should still be returned as a JSON object when it is empty.
89+
$data = (object) $data;
90+
}
91+
8692
return rest_ensure_response( $data );
8793
}
8894

tests/test-rest-taxonomies-controller.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,22 @@ public function test_get_items_invalid_permission_for_context() {
4646
$this->assertErrorResponse( 'rest_cannot_view', $response, 401 );
4747
}
4848

49-
public function test_get_taxonomies_with_types() {
49+
public function test_get_taxonomies_for_type() {
5050
$request = new WP_REST_Request( 'GET', '/wp/v2/taxonomies' );
5151
$request->set_param( 'type', 'post' );
5252
$response = $this->server->dispatch( $request );
5353
$this->check_taxonomies_for_type_response( 'post', $response );
5454
}
5555

56+
public function test_get_taxonomies_for_invalid_type() {
57+
$request = new WP_REST_Request( 'GET', '/wp/v2/taxonomies' );
58+
$request->set_param( 'type', 'wingding' );
59+
$response = $this->server->dispatch( $request );
60+
$this->assertEquals( 200, $response->get_status() );
61+
$data = $response->get_data();
62+
$this->assertEquals( json_encode( $data ), '{}' );
63+
}
64+
5665
public function test_get_item() {
5766
$request = new WP_REST_Request( 'GET', '/wp/v2/taxonomies/category' );
5867
$response = $this->server->dispatch( $request );

0 commit comments

Comments
 (0)
0