Skip to content

Commit 56bf94f

Browse files
authored
Merge pull request #568 from WordPress/fix/567-fatal-error-handling
Fix fatal error in REST API response when an image has no attachment metadata.
2 parents e0aecd7 + f93b76f commit 56bf94f

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

‎modules/images/webp-uploads/rest-api.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
*/
1919
function webp_uploads_update_rest_attachment( WP_REST_Response $response, WP_Post $post, WP_REST_Request $request ) {
2020
$data = $response->get_data();
21-
if ( ! isset( $data['media_details']['sizes'] ) || ! is_array( $data['media_details']['sizes'] ) ) {
21+
if ( ! isset( $data['media_details'] ) || ! is_array( $data['media_details'] ) || ! isset( $data['media_details']['sizes'] ) || ! is_array( $data['media_details']['sizes'] ) ) {
2222
return $response;
2323
}
2424

‎tests/modules/images/webp-uploads/rest-api-tests.php‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,39 @@ function( $transforms ) {
7171
$this->assertArrayNotHasKey( 'sources', $data['media_details'] );
7272
}
7373

74+
/**
75+
* Checks whether the media details information is added to the REST response object.
76+
*
77+
* @test
78+
*/
79+
public function it_should_check_media_details_in_rest_response() {
80+
$file_location = TESTS_PLUGIN_DIR . '/tests/testdata/modules/images/leafs.jpg';
81+
$attachment_id = $this->factory->attachment->create_upload_object( $file_location );
82+
83+
$request = new WP_REST_Request();
84+
$request['id'] = $attachment_id;
85+
86+
$controller = new WP_REST_Attachments_Controller( 'attachment' );
87+
$response = $controller->get_item( $request );
88+
89+
$this->assertNotWPError( $response );
90+
91+
$data = $response->get_data();
92+
93+
$this->assertArrayHasKey( 'media_details', $data );
94+
$this->assertIsArray( $data['media_details'] );
95+
96+
// Delete attachment metadata to set media_details as object in response.
97+
delete_post_meta( $attachment_id, '_wp_attachment_metadata' );
98+
99+
$response = $controller->get_item( $request );
100+
101+
$this->assertNotWPError( $response );
102+
103+
$data = $response->get_data();
104+
105+
$this->assertArrayHasKey( 'media_details', $data );
106+
$this->assertIsNotArray( $data['media_details'] );
107+
$this->assertIsObject( $data['media_details'] );
108+
}
74109
}

0 commit comments

Comments
 (0)