+ /**
+ * Validates setting values.
+ *
+ * Sanitization is applied to the values before being passed for validation.
+ * Validation is skipped for unregistered settings or for values that are
+ * already null since they will be skipped anyway.
+ *
+ * @since 4.6.0
+ * @access public
+ *
+ * @see WP_REST_Request::has_valid_params()
+ * @see WP_Customize_Setting::validate()
+ *
+ * @param array $setting_values Mapping of setting IDs to values to sanitize and validate.
+ * @return array Mapping of setting IDs to return value of validate method calls, either `true` or `WP_Error`.
+ */
+ public function validate_setting_values( $setting_values ) {
+ $validities = array();
+ foreach ( $setting_values as $setting_id => $unsanitized_value ) {
+ $setting = $this->get_setting( $setting_id );
+ if ( ! $setting || is_null( $unsanitized_value ) ) {
+ continue;
+ }
+ $validity = $setting->validate( $unsanitized_value );
+ if ( ! is_wp_error( $validity ) ) {
+ $value = $setting->sanitize( $unsanitized_value );
+ if ( is_null( $value ) ) {
+ $validity = false;
+ } elseif ( is_wp_error( $value ) ) {
+ $validity = $value;
+ }
+ }
+ if ( false === $validity ) {
+ $validity = new WP_Error( 'invalid_value', __( 'Invalid value.' ) );
+ }
+ $validities[ $setting_id ] = $validity;
+ }
+ return $validities;
+ }
+
+ /**
+ * Prepares setting validity for exporting to the client (JS).
+ *
+ * Converts `WP_Error` instance into array suitable for passing into the
+ * `wp.customize.Notification` JS model.
+ *
+ * @since 4.6.0
+ * @access public
+ *
+ * @param true|WP_Error $validity Setting validity.
+ * @return true|array If `$validity` was a WP_Error, the error codes will be array-mapped
+ * to their respective `message` and `data` to pass into the
+ * `wp.customize.Notification` JS model.
+ */
+ public function prepare_setting_validity_for_js( $validity ) {
+ if ( is_wp_error( $validity ) ) {
+ $notification = array();
+ foreach ( $validity->errors as $error_code => $error_messages ) {
+ $error_data = $validity->get_error_data( $error_code );
+ if ( is_null( $error_data ) ) {
+ $error_data = array();
+ }
+ $error_data = array_merge(
+ $error_data,
+ array( 'from_server' => true )
+ );
+ $notification[ $error_code ] = array(
+ 'message' => join( ' ', $error_messages ),
+ 'data' => $error_data,
+ );
+ }
+ return $notification;
+ } else {
+ return true;
+ }
+ }
+