Make WordPress Core

Opened 3 weeks ago

Last modified 3 weeks ago

#65251 new defect (bug)

Response from media library API query includes an empty array rather than an empty object

Reported by: frankieandshadow's profile frankieandshadow Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 6.9.4
Component: REST API Keywords:
Focuses: Cc:

Description

In the response to a media library query over the REST API, I am seeing that $wpimage->media_details->sizes is an empty array when there are no sizes, rather than an empty object (as a non-empty instance is an object). This discrepancy is inconsistent and breaks my recipient code. It's characteristic of json_encode being used on a keyed PHP array, when it can't tell the difference between keys and numeric indexes when empty.

I asked claude.ai to locate the bug to make it easy for you to fix. It agreed with my diagnosis and said:

File: wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php

Method: prepare_item_for_response()

The bug: when wp_get_attachment_metadata() returns metadata with an empty sizes array (image too small for sub-sizes), the method populates $data['media_details'] from that metadata but never explicitly sets $data['media_details']['sizes'] to new stdClass. The else { $data['media_details']['sizes'] = new stdClass; } branch is only reached when $metadata itself is empty/falsy. The result is that sizes is either absent or an empty PHP array [] in the JSON output, rather than {}.

Prior art: reference Trac #51393, which addressed a related inconsistency but didn't fix this code path.

Your fix suggestion: initialise $data['media_details']['sizes'] to new stdClass (or cast with (object)) before the loop that populates it, so the empty case is covered unconditionally.

Change History (1)

Note: See TracTickets for help on using tickets.