PluginProbe ʕ •ᴥ•ʔ
Kirki – Freeform Page Builder, Website Builder & Customizer / 6.0.13
Kirki – Freeform Page Builder, Website Builder & Customizer v6.0.13
6.1.1 6.1.0 6.0.14 6.0.13 6.0.12 6.0.11 6.0.10 6.0.9 6.0.8 6.0.7 6.0.6 6.0.5 6.0.4 6.0.3 6.0.2 6.0.1 3.1.3 3.1.4 3.1.5 3.1.6 3.1.7 3.1.8 3.1.9 4.0.19 4.0.20 4.0.21 4.0.22 4.0.23 4.0.24 4.1 4.2.0 5.0.0 5.1.0 5.1.1 5.2.0 5.2.1 5.2.2 5.2.3 6.0.0 trunk 3.0.40 3.0.41 3.0.42 3.0.43 3.0.44 3.0.45 3.1.0 3.1.1 3.1.2
kirki / libraries / framework / Supports / DataCaster.php
kirki / libraries / framework / Supports Last commit date
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