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
$tree
arrayrequired- The data to sanitize.
$schema
arrayrequired- The schema used for sanitization.
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. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.