1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace RemotelyLiving\PHPEnv; |
6
|
|
|
|
7
|
|
|
use RemotelyLiving\PHPEnv\Exceptions\InvalidArgument; |
8
|
|
|
|
9
|
|
|
final class StringCaster implements Interfaces\Caster |
10
|
|
|
{ |
11
|
|
|
private string $string; |
12
|
|
|
|
13
|
|
|
private function __construct(string $string) |
14
|
|
|
{ |
15
|
|
|
Assertions::assertNotEmptyString($string); |
16
|
|
|
$this->string = $string; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public static function cast(string $value): Interfaces\Caster |
20
|
|
|
{ |
21
|
|
|
return new self($value); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function asString(): string |
25
|
|
|
{ |
26
|
|
|
return $this->string; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function asInteger(): int |
30
|
|
|
{ |
31
|
|
|
return (int) round($this->asFloat()); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function asFloat(): float |
35
|
|
|
{ |
36
|
|
|
Assertions::assertNumeric($this->string); |
37
|
|
|
|
38
|
|
|
return $this->string * 1.0; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function asBoolean(): bool |
42
|
|
|
{ |
43
|
|
|
Assertions::assertBoolish($this->string); |
44
|
|
|
|
45
|
|
|
if (\mb_strtolower($this->string) === 'false') { |
46
|
|
|
return false; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return (bool) $this->string; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function asArray(string $separator = ','): array |
53
|
|
|
{ |
54
|
|
|
Assertions::assertNotEmptyString($separator); |
55
|
|
|
|
56
|
|
|
return explode($separator, $this->string); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function asUnserializedObject(): object |
60
|
|
|
{ |
61
|
|
|
try { |
62
|
|
|
$object = \unserialize($this->string); |
63
|
|
|
} catch (\Throwable $e) { |
64
|
|
|
throw InvalidArgument::unserializableValue($this->string, $e); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
Assertions::assertObject($object); |
68
|
|
|
|
69
|
|
|
return $object; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function asJSONDecodedObject(): object |
73
|
|
|
{ |
74
|
|
|
$object = json_decode($this->string); |
75
|
|
|
|
76
|
|
|
Assertions::assertObject($object); |
77
|
|
|
|
78
|
|
|
return $object; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|