Skip to content

Commit c8673ea

Browse files
extract helper function for normalization
1 parent a22f60f commit c8673ea

File tree

1 file changed

+23
-17
lines changed

1 file changed

+23
-17
lines changed

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

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,27 @@ public function get_item_permissions_check( $request ) {
194194
return current_user_can( 'read' );
195195
}
196196

197+
/**
198+
* Normalizes schema empty object defaults.
199+
*
200+
* Converts empty array defaults to objects when the schema type is 'object'
201+
* to ensure proper JSON serialization as {} instead of [].
202+
*
203+
* @since 6.9.0
204+
*
205+
* @param array<string, mixed> $schema The schema array.
206+
* @return array<string, mixed> The normalized schema.
207+
*/
208+
private function normalize_schema_empty_object_defaults( array $schema ): array {
209+
if ( isset( $schema['type'] ) && 'object' === $schema['type'] && isset( $schema['default'] ) ) {
210+
$default = $schema['default'];
211+
if ( is_array( $default ) && empty( $default ) ) {
212+
$schema['default'] = (object) $default;
213+
}
214+
}
215+
return $schema;
216+
}
217+
197218
/**
198219
* Prepares an ability for response.
199220
*
@@ -209,26 +230,11 @@ public function prepare_item_for_response( $ability, $request ) {
209230
'label' => $ability->get_label(),
210231
'description' => $ability->get_description(),
211232
'category' => $ability->get_category(),
212-
'input_schema' => $ability->get_input_schema(),
213-
'output_schema' => $ability->get_output_schema(),
233+
'input_schema' => $this->normalize_schema_empty_object_defaults( $ability->get_input_schema() ),
234+
'output_schema' => $this->normalize_schema_empty_object_defaults( $ability->get_output_schema() ),
214235
'meta' => $ability->get_meta(),
215236
);
216237

217-
// Convert top-level defaults to an object when its type is object and
218-
// they are an empty array so they get serialized as {} instead of [].
219-
if ( isset( $data['input_schema']['type'] ) && 'object' === $data['input_schema']['type'] && isset( $data['input_schema']['default'] ) ) {
220-
$default = $data['input_schema']['default'];
221-
if ( is_array( $default ) && empty( $default ) ) {
222-
$data['input_schema']['default'] = (object) $default;
223-
}
224-
}
225-
if ( isset( $data['output_schema']['type'] ) && 'object' === $data['output_schema']['type'] && isset( $data['output_schema']['default'] ) ) {
226-
$default = $data['output_schema']['default'];
227-
if ( is_array( $default ) && empty( $default ) ) {
228-
$data['output_schema']['default'] = (object) $default;
229-
}
230-
}
231-
232238
$context = $request['context'] ?? 'view';
233239
$data = $this->add_additional_fields_to_object( $data, $request );
234240
$data = $this->filter_response_by_context( $data, $context );

0 commit comments

Comments
 (0)