70 lines
1.5 KiB
PHP
70 lines
1.5 KiB
PHP
<?php
|
|
/**
|
|
* Typed accessors for mixed data (arrays from cache, options, XML).
|
|
*
|
|
* @package Fontdelbosc_Transit
|
|
*/
|
|
|
|
defined( 'ABSPATH' ) || exit;
|
|
|
|
/**
|
|
* Small typed accessor helpers.
|
|
*/
|
|
class Fontdelbosc_Transit_Payload {
|
|
|
|
/**
|
|
* Returns an array value, or the default.
|
|
*
|
|
* @param mixed $value Raw value.
|
|
* @param string $key Key to look up.
|
|
* @param mixed $default Default when the key is missing.
|
|
* @return mixed
|
|
*/
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* 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 an array value.
|
|
*
|
|
* @param mixed $value Raw value.
|
|
* @return array<int|string, mixed>
|
|
*/
|
|
public static function arr( mixed $value ): array {
|
|
return is_array( $value ) ? $value : array();
|
|
}
|
|
}
|