forked from php-soap/encoding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionalElementEncoder.php
More file actions
66 lines (58 loc) · 1.92 KB
/
Copy pathOptionalElementEncoder.php
File metadata and controls
66 lines (58 loc) · 1.92 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
<?php
declare(strict_types=1);
namespace Soap\Encoding\Encoder;
use Soap\Encoding\Xml\Node\Element;
use Soap\Encoding\Xml\Writer\NilAttributeBuilder;
use Soap\Encoding\Xml\Writer\XsdTypeXmlElementWriter;
use VeeWee\Reflecta\Iso\Iso;
use VeeWee\Xml\Xmlns\Xmlns;
/**
* @template T of mixed
* @implements XmlEncoder<T, string>
*/
final class OptionalElementEncoder implements Feature\ElementAware, Feature\OptionalAware, XmlEncoder
{
/**
* @param XmlEncoder<T, string> $elementEncoder
*/
public function __construct(
private readonly XmlEncoder $elementEncoder
) {
}
/**
* @return Iso<T, string>
*/
public function iso(Context $context): Iso
{
$type = $context->type;
$meta = $type->getMeta();
$elementIso = $this->elementEncoder->iso($context);
if (!$meta->isNullable()->unwrapOr(false)) {
return $elementIso;
}
return new Iso(
/**
* @param T|null $raw
*/
static fn (mixed $raw): string => match (true) {
$raw === null && $meta->isNil()->unwrapOr(false) => (new XsdTypeXmlElementWriter())($context, new NilAttributeBuilder()),
$raw === null => '',
default => $elementIso->to($raw),
},
/**
* @return T|null
*/
static function (Element|string $xml) use ($elementIso) : mixed {
if ($xml === '') {
return null;
}
$documentElement = ($xml instanceof Element ? $xml : Element::fromString($xml))->element();
if ($documentElement->getAttributeNS(Xmlns::xsi()->value(), 'nil') === 'true') {
return null;
}
/** @var Iso<T|null, Element|non-empty-string> $elementIso */
return $elementIso->from($xml);
}
);
}
}