93 lines
2 KiB
PHP
93 lines
2 KiB
PHP
<?php
|
|
/**
|
|
* Typed access helpers for mixed JSON payload values.
|
|
*
|
|
* @package FontdelboscCombustible
|
|
*/
|
|
|
|
declare( strict_types=1 );
|
|
|
|
defined( 'ABSPATH' ) || exit;
|
|
|
|
/**
|
|
* Static helper to read mixed API values with predictable types.
|
|
*/
|
|
final class Fontdelbosc_Combustible_Payload {
|
|
|
|
/**
|
|
* Returns an array value for a possibly missing or mixed key.
|
|
*
|
|
* @param mixed $value Raw value.
|
|
* @param array<mixed> $default Fallback.
|
|
* @return array<mixed>
|
|
*/
|
|
public static function arr( mixed $value, array $default = array() ): array {
|
|
return is_array( $value ) ? $value : $default;
|
|
}
|
|
|
|
/**
|
|
* Returns a string value for a possibly missing or mixed key.
|
|
*
|
|
* @param mixed $value Raw value.
|
|
*/
|
|
public static function str( mixed $value ): ?string {
|
|
return is_string( $value ) ? trim( $value ) : null;
|
|
}
|
|
|
|
/**
|
|
* Returns an int value for a possibly missing or mixed key.
|
|
*
|
|
* @param mixed $value Raw value.
|
|
*/
|
|
public static function int( mixed $value ): ?int {
|
|
if ( is_int( $value ) ) {
|
|
return $value;
|
|
}
|
|
|
|
if ( is_float( $value ) ) {
|
|
return (int) $value;
|
|
}
|
|
|
|
if ( is_string( $value ) && preg_match( '/^-?\d+$/', trim( $value ) ) ) {
|
|
return (int) $value;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Returns a float value for a possibly missing or mixed key.
|
|
*
|
|
* @param mixed $value Raw value.
|
|
*/
|
|
public static function float( mixed $value ): ?float {
|
|
if ( is_float( $value ) ) {
|
|
return $value;
|
|
}
|
|
|
|
if ( is_int( $value ) ) {
|
|
return (float) $value;
|
|
}
|
|
|
|
if ( is_string( $value ) && is_numeric( trim( $value ) ) ) {
|
|
return (float) trim( $value );
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Returns a key from an array with a default, null-safe.
|
|
*
|
|
* @param mixed $value Haystack.
|
|
* @param string $key Key.
|
|
* @param mixed $default Fallback.
|
|
*/
|
|
public static function get( mixed $value, string $key, mixed $default = null ): mixed {
|
|
if ( is_array( $value ) && array_key_exists( $key, $value ) ) {
|
|
return $value[ $key ];
|
|
}
|
|
|
|
return $default;
|
|
}
|
|
}
|