forked from php-soap/encoding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScalarTypeEncoder.php
More file actions
81 lines (72 loc) · 2.6 KB
/
ScalarTypeEncoder.php
File metadata and controls
81 lines (72 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
declare(strict_types=1);
namespace Soap\Encoding\Encoder\SimpleType;
use Psl\Type;
use Soap\Encoding\Encoder\Context;
use Soap\Encoding\Encoder\XmlEncoder;
use Soap\Encoding\Exception\RestrictionException;
use VeeWee\Reflecta\Iso\Iso;
use function is_bool;
use function is_float;
use function is_int;
use function is_string;
/**
* @implements XmlEncoder<mixed, string>
*/
final class ScalarTypeEncoder implements XmlEncoder
{
public static function default(): self
{
/** @psalm-var ScalarTypeEncoder $instance */
static $instance = new self();
return $instance;
}
/**
* Will parse scalar values but accepts mixed to throw exceptions on invalid types.
*
* @return Iso<mixed, string>
*/
public function iso(Context $context): Iso
{
$intIso = (new IntTypeEncoder())->iso($context);
$floatIso = (new FloatTypeEncoder())->iso($context);
$stringIso = (new StringTypeEncoder())->iso($context);
$boolIso = (new BoolTypeEncoder())->iso($context);
return (new Iso(
static fn (mixed $value): string => match(true) {
is_int($value) => $intIso->to($value),
is_float($value) => $floatIso->to($value),
is_string($value) => $stringIso->to($value),
is_bool($value) => $boolIso->to($value),
default => throw RestrictionException::unsupportedValueType($context->type, $value)
},
static function (string $value) use ($context): mixed {
try {
return Type\int()->coerce($value);
} catch (Type\Exception\CoercionException) {
}
try {
return Type\float()->coerce($value);
} catch (Type\Exception\CoercionException) {
}
try {
return Type\converted(
Type\string(),
Type\bool(),
static fn (string $value): bool => match ($value) {
'true' => true,
'false' => false,
default => throw RestrictionException::unexpectedEnumType(
$context->type,
['true', 'false'],
$value
)
}
)->coerce($value);
} catch (Type\Exception\CoercionException) {
}
return Type\string()->coerce($value);
}
));
}
}