Skip to content

Commit 09a9620

Browse files
committed
Abilities API: Normalize input from schema
1 parent 871fd0e commit 09a9620

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/wp-includes/abilities-api/class-wp-ability.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,31 @@ public function get_meta_item( string $key, $default_value = null ) {
400400
return array_key_exists( $key, $this->meta ) ? $this->meta[ $key ] : $default_value;
401401
}
402402

403+
/**
404+
* Normalizes the input for the ability, applying the default value from the input schema when needed.
405+
*
406+
* When no input is provided and the input schema is defined with a top-level `default` key, this method returns
407+
* the value of that key. If the input schema does not define a `default`, or if the input schema is empty,
408+
* this method returns null. If input is provided, it is returned as-is.
409+
*
410+
* @since 6.9.0
411+
*
412+
* @param mixed $input Optional. The raw input provided for the ability. Default `null`.
413+
* @return mixed The same input, or the default from schema, or `null` if default not set.
414+
*/
415+
public function normalize_input( $input = null ) {
416+
if ( null !== $input ) {
417+
return $input;
418+
}
419+
420+
$input_schema = $this->get_input_schema();
421+
if ( ! empty( $input_schema ) && array_key_exists( 'default', $input_schema ) ) {
422+
return $input_schema['default'];
423+
}
424+
425+
return null;
426+
}
427+
403428
/**
404429
* Validates input data against the input schema.
405430
*
@@ -536,6 +561,7 @@ protected function validate_output( $output ) {
536561
* @return mixed|WP_Error The result of the ability execution, or WP_Error on failure.
537562
*/
538563
public function execute( $input = null ) {
564+
$input = $this->sanitize_input( $input );
539565
$is_valid = $this->validate_input( $input );
540566
if ( is_wp_error( $is_valid ) ) {
541567
return $is_valid;

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,7 @@ public function check_ability_permissions( $request ) {
159159
}
160160

161161
$input = $this->get_input_from_request( $request );
162+
$input = $ability->normalize_input( $input );
162163
$is_valid = $ability->validate_input( $input );
163164
if ( is_wp_error( $is_valid ) ) {
164165
$is_valid->add_data( array( 'status' => 400 ) );

0 commit comments

Comments
 (0)