W3cubDocs

/WordPress

WP_Font_Utils::sanitize_from_schema( array $tree, array $schema ): array

Sanitizes a tree of data using a schema.

Description

The schema structure should mirror the data tree. Each value provided in the schema should be a callable that will be applied to sanitize the corresponding value in the data tree. Keys that are in the data tree, but not present in the schema, will be removed in the sanitized data. Nested arrays are traversed recursively.

Parameters

$treearrayrequired
The data to sanitize.
$schemaarrayrequired
The schema used for sanitization.

Return

array The sanitized data.

Source

public static function sanitize_from_schema( $tree, $schema ) {
	if ( ! is_array( $tree ) || ! is_array( $schema ) ) {
		return array();
	}

	foreach ( $tree as $key => $value ) {
		// Remove keys not in the schema or with null/empty values.
		if ( ! array_key_exists( $key, $schema ) ) {
			unset( $tree[ $key ] );
			continue;
		}

		$is_value_array  = is_array( $value );
		$is_schema_array = is_array( $schema[ $key ] ) && ! is_callable( $schema[ $key ] );

		if ( $is_value_array && $is_schema_array ) {
			if ( wp_is_numeric_array( $value ) ) {
				// If indexed, process each item in the array.
				foreach ( $value as $item_key => $item_value ) {
					$tree[ $key ][ $item_key ] = isset( $schema[ $key ][0] ) && is_array( $schema[ $key ][0] )
						? self::sanitize_from_schema( $item_value, $schema[ $key ][0] )
						: self::apply_sanitizer( $item_value, $schema[ $key ][0] );
				}
			} else {
				// If it is an associative or indexed array, process as a single object.
				$tree[ $key ] = self::sanitize_from_schema( $value, $schema[ $key ] );
			}
		} elseif ( ! $is_value_array && $is_schema_array ) {
			// If the value is not an array but the schema is, remove the key.
			unset( $tree[ $key ] );
		} elseif ( ! $is_schema_array ) {
			// If the schema is not an array, apply the sanitizer to the value.
			$tree[ $key ] = self::apply_sanitizer( $value, $schema[ $key ] );
		}

		// Remove keys with null/empty values.
		if ( empty( $tree[ $key ] ) ) {
			unset( $tree[ $key ] );
		}
	}

	return $tree;
}

Changelog

Version Description
6.5.0 Introduced.

© 2003–2024 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/classes/wp_font_utils/sanitize_from_schema