-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathErrorHandlingEncoder.php
84 lines (75 loc) · 2.25 KB
/
ErrorHandlingEncoder.php
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
82
83
84
<?php
declare(strict_types=1);
namespace Soap\Encoding\Encoder;
use Soap\Encoding\Exception\EncodingException;
use Throwable;
use VeeWee\Reflecta\Iso\Iso;
/**
* @template-covariant TData
* @template-covariant TXml
*
* @implements XmlEncoder<TData, TXml>
* @implements Feature\DecoratingEncoder<TData, TXml>
*/
final class ErrorHandlingEncoder implements Feature\DecoratingEncoder, XmlEncoder
{
/**
* @param XmlEncoder<TData, TXml> $encoder
*/
public function __construct(
private readonly XmlEncoder $encoder
) {
}
/**
* @return XmlEncoder<TData, TXml>
*/
public function decoratedEncoder(): XmlEncoder
{
return $this->encoder;
}
/**
* @return Iso<TData, TXml>
*/
public function iso(Context $context): Iso
{
$innerIso = $this->encoder->iso($context);
return new Iso(
/**
* @psalm-param TData $value
* @psalm-return TXml
*/
static function (mixed $value) use ($innerIso, $context): mixed {
try {
return $innerIso->to($value);
} catch (Throwable $exception) {
throw EncodingException::encodingValue($value, $context->type, $exception, self::buildPath($context));
}
},
/**
* @psalm-param TXml $value
* @psalm-return TData
*/
static function (mixed $value) use ($innerIso, $context): mixed {
try {
return $innerIso->from($value);
} catch (Throwable $exception) {
throw EncodingException::decodingValue($value, $context->type, $exception, self::buildPath($context));
}
}
);
}
private static function buildPath(Context $context): ?string
{
$meta = $context->type->getMeta();
$isElement = $meta->isElement()->unwrapOr(false);
$isAttribute = $meta->isAttribute()->unwrapOr(false);
if (!$isElement && !$isAttribute) {
return null;
}
$path = $context->type->getXmlTargetNodeName();
if ($isAttribute) {
return '@' . $path;
}
return $path;
}
}