This commit is contained in:
Javier Casares 2026-10-12 11:55:23 +00:00
commit 06153e387d
47 changed files with 5116 additions and 0 deletions

View file

@ -0,0 +1,88 @@
<?php
/**
* Typed helpers to navigate decoded JSON payloads without casting mixed values.
*
* @package FontdelboscEltemps
*/
defined( 'ABSPATH' ) || exit;
/**
* Narrowing helpers for mixed JSON values.
*/
final class Fontdelbosc_Payload {
/**
* Walks a nested array path and returns the value at the end, or null.
*
* @param mixed $value Starting value.
* @param int|string|null ...$keys Path keys.
* @return mixed
*/
public static function path( mixed $value, int|string|null ...$keys ): mixed {
foreach ( $keys as $key ) {
if ( null === $key || ! is_array( $value ) ) {
return null;
}
$value = $value[ $key ] ?? null;
}
return $value;
}
/**
* Returns the value at a key, or null when the holder is not an array.
*
* @param mixed $value Holder.
* @param int|string $key Key.
* @return mixed
*/
public static function get( mixed $value, int|string $key ): mixed {
if ( ! is_array( $value ) ) {
return null;
}
return $value[ $key ] ?? null;
}
/**
* Returns the value as an array, or an empty array.
*
* @param mixed $value Raw value.
* @return array<mixed>
*/
public static function arr( mixed $value ): array {
return is_array( $value ) ? $value : array();
}
/**
* Returns the value as a string, or null.
*
* @param mixed $value Raw value.
* @return string|null
*/
public static function str( mixed $value ): ?string {
return is_string( $value ) ? $value : null;
}
/**
* Returns the value as an integer, or null.
*
* @param mixed $value Raw value.
* @return int|null
*/
public static function int( mixed $value ): ?int {
return is_numeric( $value ) ? (int) round( (float) $value ) : null;
}
/**
* Returns the value as a float, or null.
*
* @param mixed $value Raw value.
* @return float|null
*/
public static function float( mixed $value ): ?float {
return is_numeric( $value ) ? (float) $value : null;
}
}