Facades
3 weeks ago
Traits
3 weeks ago
Arr.php
3 weeks ago
DataCaster.php
3 weeks ago
Flex.php
3 weeks ago
HigherOrderTapProxy.php
3 weeks ago
MediaAttachment.php
3 weeks ago
MessagesBag.php
3 weeks ago
Str.php
3 weeks ago
Url.php
3 weeks ago
Utils.php
3 weeks ago
DataCaster.php
92 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Utility for casting values and nested structures to scalar and collection types. |
| 5 | * Normalizes request, option, and model data before validation and persistence layers consume it. |
| 6 | * Keeps type coercion logic out of controllers and repositories. |
| 7 | * |
| 8 | * @package Framework |
| 9 | * @subpackage Supports |
| 10 | * @since 1.0.0 |
| 11 | */ |
| 12 | namespace Kirki\Framework\Supports; |
| 13 | |
| 14 | \defined('ABSPATH') || exit; |
| 15 | use Exception; |
| 16 | class DataCaster |
| 17 | { |
| 18 | /** |
| 19 | * Cast a value to the given type. |
| 20 | * |
| 21 | * @param mixed $value The value. |
| 22 | * @param mixed $type The type. |
| 23 | * |
| 24 | * @return mixed |
| 25 | * |
| 26 | * @since 1.0.0 |
| 27 | */ |
| 28 | public static function cast_value($value, $type = null) |
| 29 | { |
| 30 | if (\is_null($type)) { |
| 31 | return $value; |
| 32 | } |
| 33 | switch (\strtolower($type)) { |
| 34 | case 'int': |
| 35 | case 'integer': |
| 36 | return (int) $value; |
| 37 | case 'float': |
| 38 | case 'double': |
| 39 | return (float) $value; |
| 40 | case 'bool': |
| 41 | case 'boolean': |
| 42 | return (bool) $value; |
| 43 | case 'string': |
| 44 | return (string) $value; |
| 45 | case 'array': |
| 46 | if (\is_array($value)) { |
| 47 | return $value; |
| 48 | } |
| 49 | if (\is_string($value)) { |
| 50 | $decoded = \json_decode($value, \true); |
| 51 | if (\json_last_error() === \JSON_ERROR_NONE && \is_array($decoded)) { |
| 52 | return $decoded; |
| 53 | } |
| 54 | return [$value]; |
| 55 | } |
| 56 | // For anything else (int, bool, object, etc.) cast to array directly |
| 57 | return [$value]; |
| 58 | default: |
| 59 | return $value; |
| 60 | } |
| 61 | } |
| 62 | /** |
| 63 | * Cast an array or object using a type map. |
| 64 | * |
| 65 | * @param mixed $data The data payload. |
| 66 | * @param mixed $map The map. |
| 67 | * |
| 68 | * @return array |
| 69 | * |
| 70 | * @throws \Exception |
| 71 | * |
| 72 | * @since 1.0.0 |
| 73 | */ |
| 74 | public static function cast_data($data, $map) |
| 75 | { |
| 76 | if (!\is_array($data) && !\is_object($data)) { |
| 77 | throw new Exception('Data must be either an array or an object'); |
| 78 | } |
| 79 | if (\is_object($data)) { |
| 80 | foreach ($map as $key => $type) { |
| 81 | $data->{$key} = static::cast_value($data->{$key}, $type); |
| 82 | } |
| 83 | } |
| 84 | if (\is_array($data)) { |
| 85 | foreach ($map as $key => $type) { |
| 86 | $data[$key] = static::cast_value($data[$key], $type); |
| 87 | } |
| 88 | } |
| 89 | return $data; |
| 90 | } |
| 91 | } |
| 92 |