WordPress.org

Make WordPress Core


Ignore:
Timestamp:
10/31/2016 01:47:36 AM (4 years ago)
Author:
pento
Message:

REST API: Add support for arrays in schema validation and sanitization.

By allowing more fine-grained validation and sanitisation of endpoint args, we can ensure the correct data is being passed to endpoints.

This can easily be extended to support new data types, such as CSV fields or objects.

Props joehoyle, rachelbaker, pento.
Fixes #38531.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-settings-controller.php

    r39030 r39046  
    289289        foreach ( $options as $option_name => $option ) {
    290290            $schema['properties'][ $option_name ] = $option['schema'];
     291            $schema['properties'][ $option_name ]['arg_options'] = array(
     292                'sanitize_callback' => array( $this, 'sanitize_callback' ),
     293            );
    291294        }
    292295
    293296        return $this->add_additional_fields_schema( $schema );
    294297    }
     298
     299    /**
     300     * Custom sanitize callback used for all options to allow the use of 'null'.
     301     *
     302     * By default, the schema of settings will throw an error if a value is set to
     303     * `null` as it's not a valid value for something like "type => string". We
     304     * provide a wrapper sanitizer to whitelist the use of `null`.
     305     *
     306     * @param  mixed           $value   The value for the setting.
     307     * @param  WP_REST_Request $request The request object.
     308     * @param  string          $param   The parameter name.
     309     * @return mixed|WP_Error
     310     */
     311    public function sanitize_callback( $value, $request, $param ) {
     312        if ( is_null( $value ) ) {
     313            return $value;
     314        }
     315        return rest_parse_request_arg( $value, $request, $param );
     316    }
    295317}
Note: See TracChangeset for help on using the changeset viewer.