From 147c9baf4f2eb3e8209d1c2d54c15ed58404683f Mon Sep 17 00:00:00 2001 From: vedanshujain Date: Thu, 13 Aug 2020 13:30:39 +0530 Subject: [PATCH] Change `mixed` data type to composite for compatibility with 5.5 --- .../Version3/class-wc-rest-controller.php | 53 ++++++++++++++++--- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/includes/rest-api/Controllers/Version3/class-wc-rest-controller.php b/includes/rest-api/Controllers/Version3/class-wc-rest-controller.php index 9365efbe7b3..6aa4284df9e 100644 --- a/includes/rest-api/Controllers/Version3/class-wc-rest-controller.php +++ b/includes/rest-api/Controllers/Version3/class-wc-rest-controller.php @@ -93,16 +93,53 @@ abstract class WC_REST_Controller extends WP_REST_Controller { return $endpoint_args; } - foreach ( $endpoint_args as $field_id => $params ) { - /** - * Custom types are not supported as of WP 5.5, this translates type => 'date-time' to type => 'string' with format date-time. - */ - if ( 'date-time' === $params['type'] ) { - $endpoint_args[ $field_id ]['type'] = 'string'; - $endpoint_args[ $field_id ]['format'] = 'date-time'; - } + $endpoint_args = $this->adjust_wp_5_5_datatype_compatibility( $endpoint_args ); + + return $endpoint_args; + } + + /** + * Change datatypes `date-time` to string, and `mixed` to composite of all built in types. + * + * @param array $endpoint_args Schema with datatypes to convert. + + * @return mixed Schema with converted datatype. + */ + protected function adjust_wp_5_5_datatype_compatibility( $endpoint_args ) { + if ( version_compare( get_bloginfo( 'version' ), '5.5', '<' ) ) { + return $endpoint_args; } + foreach ( $endpoint_args as $field_id => $params ) { + + if ( ! isset( $params['type'] ) ) { + continue; + } + + /** + * Custom types are not supported as of WP 5.5, this translates type => 'date-time' to type => 'string'. + */ + if ( 'date-time' === $params['type'] ) { + $params['type'] = 'string'; + } + + /** + * WARNING: Order of fields here is important, types of fields are ordered from most specific to least specific as perceived by core's built-in type validation methods. + */ + if ( 'mixed' === $params['type'] ) { + $params['type'] = array( 'object', 'string', 'number', 'boolean', 'integer', 'array', 'null' ); + } + + if ( isset( $params['properties'] ) ) { + $params['properties'] = $this->adjust_wp_5_5_datatype_compatibility( $params['properties'] ); + } + + if ( isset( $params['items'] ) && isset( $params['items']['properties'] ) ) { + $params['items']['properties'] = $this->adjust_wp_5_5_datatype_compatibility( $params['items']['properties'] ); + } + + $endpoint_args[ $field_id ] = $params; + } return $endpoint_args; }