<?php
/**
 * Shared recursive sanitizer for admin REST payloads.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Admin\Rest;

defined( 'ABSPATH' ) || exit;

/**
 * Recursively sanitizes arbitrary JSON-decoded REST payloads while
 * preserving key casing and numeric array indexes.
 */
class RestSanitizer {

	/**
	 * Recursively sanitize a value.
	 *
	 * @param mixed $value Value.
	 * @param int   $depth Depth.
	 * @return mixed
	 */
	public static function sanitize_recursive( $value, $depth = 0 ) {
		if ( $depth > 25 ) {
			return null;
		}

		if ( is_bool( $value ) || is_null( $value ) ) {
			return $value;
		}

		if ( is_int( $value ) || is_float( $value ) ) {
			return $value;
		}

		if ( is_string( $value ) ) {
			return sanitize_text_field( $value );
		}

		if ( is_array( $value ) ) {
			$sanitized = array();
			foreach ( $value as $k => $v ) {
				// Preserve keys (camelCase) for the admin app.
				// Also convert numeric string indexes back to ints to keep JSON arrays as arrays.
				$key = $k;
				if ( is_string( $k ) && ctype_digit( $k ) ) {
					$key = (int) $k;
				}
				$sanitized[ $key ] = self::sanitize_recursive( $v, $depth + 1 );
			}
			return $sanitized;
		}

		return null;
	}
}
