forked from php-soap/encoding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAttributeValueEncoder.php
More file actions
72 lines (61 loc) · 1.9 KB
/
AttributeValueEncoder.php
File metadata and controls
72 lines (61 loc) · 1.9 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
<?php
declare(strict_types=1);
namespace Soap\Encoding\Encoder\SimpleType;
use Soap\Encoding\Encoder\Context;
use Soap\Encoding\Encoder\XmlEncoder;
use Soap\Encoding\Exception\RestrictionException;
use VeeWee\Reflecta\Iso\Iso;
use function Psl\Type\scalar;
/**
* @implements XmlEncoder<mixed, string|null>
*/
final class AttributeValueEncoder implements XmlEncoder
{
/**
* @param XmlEncoder<mixed, string> $typeEncoder
*/
public function __construct(
private readonly XmlEncoder $typeEncoder
) {
}
/**
* @return Iso<mixed, string|null>
*/
public function iso(Context $context): Iso
{
$typeIso = $this->typeEncoder->iso($context);
return (new Iso(
fn (mixed $value): ?string => $this->to($context, $typeIso, $value),
fn (?string $value): mixed => $this->from($context, $typeIso, $value),
));
}
/**
* @param Iso<mixed, string> $typeIso
*/
private function to(Context $context, Iso $typeIso, mixed $value): ?string
{
$meta = $context->type->getMeta();
$fixed = $meta->fixed()
->map(static fn (string $fixed): mixed => $typeIso->from($fixed))
->unwrapOr(null);
if ($fixed !== null && $value !== $fixed) {
throw RestrictionException::invalidFixedValue(
scalar()->assert($fixed),
scalar()->assert($value)
);
}
return $value !== null ? $typeIso->to($value) : null;
}
/**
* @param Iso<mixed, string> $typeIso
*/
private function from(Context $context, Iso $typeIso, ?string $value): mixed
{
if ($value !== null) {
return $typeIso->from($value);
}
$meta = $context->type->getMeta();
$default = $meta->fixed()->or($meta->default())->unwrapOr(null);
return $default !== null ? $typeIso->from($default) : null;
}
}