| 1 |
<?php |
| 2 |
/** |
| 3 |
* Scalar value casting. |
| 4 |
* |
| 5 |
* @package Disco |
| 6 |
* @subpackage \App\Utility |
| 7 |
*/ |
| 8 |
|
| 9 |
namespace Disco\App\Utility; |
| 10 |
|
| 11 |
/** |
| 12 |
* Casts untyped campaign / cart values to scalars. |
| 13 |
* |
| 14 |
* Campaign rules come out of a JSON column and cart items out of WooCommerce |
| 15 |
* session data, so quantities and ids arrive as strings, nulls or occasionally |
| 16 |
* arrays. These casts keep calling code free of defensive `is_numeric()` noise |
| 17 |
* and return a harmless zero for anything unusable. |
| 18 |
* |
| 19 |
* @package Disco |
| 20 |
* @subpackage Disco\App\Utility |
| 21 |
* @category Utility |
| 22 |
*/ |
| 23 |
class Value { |
| 24 |
|
| 25 |
/** |
| 26 |
* Cast a raw value to int, or 0 when it is not numeric. |
| 27 |
* |
| 28 |
* @param mixed $value Raw value. |
| 29 |
*/ |
| 30 |
public static function to_int( $value ): int { |
| 31 |
if ( ! is_numeric( $value ) ) { |
| 32 |
return 0; |
| 33 |
} |
| 34 |
|
| 35 |
return (int) $value; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Cast a raw value to float, or 0.0 when it is not numeric. |
| 40 |
* |
| 41 |
* @param mixed $value Raw value. |
| 42 |
*/ |
| 43 |
public static function to_float( $value ): float { |
| 44 |
if ( ! is_numeric( $value ) ) { |
| 45 |
return 0.0; |
| 46 |
} |
| 47 |
|
| 48 |
return (float) $value; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Cast a raw value to string, or '' when it is not scalar. |
| 53 |
* |
| 54 |
* @param mixed $value Raw value. |
| 55 |
*/ |
| 56 |
public static function to_string( $value ): string { |
| 57 |
if ( ! is_scalar( $value ) ) { |
| 58 |
return ''; |
| 59 |
} |
| 60 |
|
| 61 |
return (string) $value; |
| 62 |
} |
| 63 |
|
| 64 |
} |
| 65 |
|