Bazujące na WordPress narzędzie wyszukiwania dla deweloperów i twórców motywów.



rest_sanitize_value_from_schema ›

Od4.7.0
Przestarzałyn/a
rest_sanitize_value_from_schema ( $value, $args )
Parametry: (2)
  • (mixed) $value The value to sanitize.
    Wymagane: Tak
  • (array) $args Schema array to use for sanitization.
    Wymagane: Tak
Powrót:
  • (true|WP_Error)
Zdefiniowane na:
Codex:

Sanitize a value based on a schema.



Źródło

function rest_sanitize_value_from_schema( $value, $args ) {
	if ( is_array( $args['type'] ) ) {
		// Determine which type the value was validated against, and use that type when performing sanitization
		$validated_type = '';

		foreach ( $args['type'] as $type ) {
			$type_args         = $args;
			$type_args['type'] = $type;

			if ( ! is_wp_error( rest_validate_value_from_schema( $value, $type_args ) ) ) {
				$validated_type = $type;
				break;
			}
		}

		if ( ! $validated_type ) {
			return null;
		}

		$args['type'] = $validated_type;
	}

	if ( 'array' === $args['type'] ) {
		if ( empty( $args['items'] ) ) {
			return (array) $value;
		}
		$value = wp_parse_list( $value );
		foreach ( $value as $index => $v ) {
			$value[ $index ] = rest_sanitize_value_from_schema( $v, $args['items'] );
		}
		// Normalize to numeric array so nothing unexpected
		// is in the keys.
		$value = array_values( $value );
		return $value;
	}

	if ( 'object' === $args['type'] ) {
		if ( $value instanceof stdClass ) {
			$value = (array) $value;
		}

		if ( $value instanceof JsonSerializable ) {
			$value = $value->jsonSerialize();
		}

		if ( ! is_array( $value ) ) {
			return array();
		}

		foreach ( $value as $property => $v ) {
			if ( isset( $args['properties'][ $property ] ) ) {
				$value[ $property ] = rest_sanitize_value_from_schema( $v, $args['properties'][ $property ] );
			} elseif ( isset( $args['additionalProperties'] ) ) {
				if ( false === $args['additionalProperties'] ) {
					unset( $value[ $property ] );
				} elseif ( is_array( $args['additionalProperties'] ) ) {
					$value[ $property ] = rest_sanitize_value_from_schema( $v, $args['additionalProperties'] );
				}
			}
		}

		return $value;
	}

	if ( 'null' === $args['type'] ) {
		return null;
	}

	if ( 'integer' === $args['type'] ) {
		return (int) $value;
	}

	if ( 'number' === $args['type'] ) {
		return (float) $value;
	}

	if ( 'boolean' === $args['type'] ) {
		return rest_sanitize_boolean( $value );
	}

	if ( isset( $args['format'] ) ) {
		switch ( $args['format'] ) {
			case 'date-time':
				return sanitize_text_field( $value );

			case 'email':
				/*
				 * sanitize_email() validates, which would be unexpected.
				 */
				return sanitize_text_field( $value );

			case 'uri':
				return esc_url_raw( $value );

			case 'ip':
				return sanitize_text_field( $value );
		}
	}

	if ( 'string' === $args['type'] ) {
		return strval( $value );
	}

	return $value;
}