1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PhpWinTools\WmiScripting\Concerns; |
4
|
|
|
|
5
|
|
|
use PhpWinTools\Support\BooleanModule; |
6
|
|
|
use function PhpWinTools\WmiScripting\Support\class_has_property; |
7
|
|
|
use function PhpWinTools\WmiScripting\Support\get_ancestor_property; |
8
|
|
|
|
9
|
|
|
trait HasCastableAttributes |
10
|
|
|
{ |
11
|
|
|
protected $casts_booted = false; |
12
|
|
|
|
13
|
|
|
public function getCasts(): array |
14
|
|
|
{ |
15
|
|
|
if (!$this->casts_booted) { |
16
|
|
|
$this->bootCasts(); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
return $this->attribute_casting; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function getCast($attribute) |
23
|
|
|
{ |
24
|
|
|
$casts = $this->getCasts(); |
25
|
|
|
|
26
|
|
|
return $casts[$attribute] ?? null; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function hasCast($attribute): bool |
30
|
|
|
{ |
31
|
|
|
return array_key_exists($attribute, $this->getCasts()); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
protected function cast($key, $value) |
35
|
|
|
{ |
36
|
|
|
$casts = $this->getCasts(); |
37
|
|
|
|
38
|
|
|
if (!$this->hasCast($key)) { |
39
|
|
|
return $value; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
switch ($casts[$key]) { |
43
|
|
|
case 'array': |
44
|
|
|
return is_array($value) ? $value : [$value]; |
45
|
|
|
case 'bool': |
46
|
|
|
case 'boolean': |
47
|
|
|
return BooleanModule::makeBoolean($value); |
48
|
|
|
case 'int': |
49
|
|
|
case 'integer': |
50
|
|
|
// Prevent integer overflow |
51
|
|
|
return $value >= PHP_INT_MAX || $value <= PHP_INT_MIN ? (string) $value : (int) $value; |
52
|
|
|
case 'string': |
53
|
|
|
if ($value === true) { |
54
|
|
|
return 'true'; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
if ($value === false) { |
58
|
|
|
return 'false'; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if (is_array($value)) { |
62
|
|
|
return json_encode($value); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return (string) $value; |
66
|
|
|
default: |
67
|
|
|
return $value; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
protected function bootCasts() |
72
|
|
|
{ |
73
|
|
|
$merge_casting = true; |
74
|
|
|
$attribute_casting = []; |
75
|
|
|
|
76
|
|
|
if (class_has_property(get_called_class(), 'merge_parent_casting')) { |
77
|
|
|
$merge_casting = $this->merge_parent_casting; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
if (class_has_property(get_called_class(), 'attribute_casting')) { |
81
|
|
|
$attribute_casting = $this->attribute_casting; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
$this->attribute_casting = $merge_casting |
|
|
|
|
85
|
|
|
? array_merge(get_ancestor_property(get_called_class(), 'attribute_casting'), $attribute_casting) |
86
|
|
|
: $attribute_casting; |
87
|
|
|
|
88
|
|
|
$this->casts_booted = true; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|