Make WordPress Core


Ignore:
Timestamp:
10/22/2025 03:02:29 PM (6 months ago)
Author:
gziolo
Message:

Abilities API: Normalize input from schema

Without this patch REST API would require a weird empty ?input field for optional input given how the current controller works with input schema when it defines the expected shape. This patch normalizes the input for the ability, applying the default value from the input schema when needed.

Developed in https://github.com/WordPress/wordpress-develop/pull/10395.

Follow-up [61032], [61045].

Props gziolo, jorgefilipecosta, mukesh27.
Fixes #64139.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/abilities-api/class-wp-ability.php

    r61032 r61047  
    402402
    403403    /**
     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
     428    /**
    404429     * Validates input data against the input schema.
    405430     *
     
    537562     */
    538563    public function execute( $input = null ) {
     564        $input    = $this->normalize_input( $input );
    539565        $is_valid = $this->validate_input( $input );
    540566        if ( is_wp_error( $is_valid ) ) {
Note: See TracChangeset for help on using the changeset viewer.