|
| 1 | +<?php declare(strict_types=1); |
| 2 | +require_once \dirname(__DIR__, 3) . '/vendor/autoload.php'; |
| 3 | + |
| 4 | +use Soap\Encoding\Encoder\Context; |
| 5 | +use Soap\Encoding\Encoder\Feature\ElementAware; |
| 6 | +use Soap\Encoding\Encoder\SimpleType\ScalarTypeEncoder; |
| 7 | +use Soap\Encoding\Encoder\XmlEncoder; |
| 8 | +use Soap\Encoding\EncoderRegistry; |
| 9 | +use VeeWee\Reflecta\Iso\Iso; |
| 10 | +use function VeeWee\Xml\Encoding\document_encode; |
| 11 | +use function VeeWee\Xml\Encoding\xml_decode; |
| 12 | + |
| 13 | +/** |
| 14 | + * Most of the time, you don't need access to the wrapping XML element from within a simple type encoder. |
| 15 | + * Sometimes, when using anyXml or anyType, you might want to have full control over the wrapping element. |
| 16 | + * This allows you to use 3rd party tools to build the full XML structure from within a simple type encoder. |
| 17 | + * |
| 18 | + * Do note that: |
| 19 | + * - You'll need to check if the current provided type is an attribute or not. |
| 20 | + * - If you want to add xsi:type information, you need to add / parse it manually. |
| 21 | + * - The result will be used as a raw XML input, meaning it should be valid XML (without the header declearations). |
| 22 | + */ |
| 23 | +EncoderRegistry::default() |
| 24 | + ->addSimpleTypeConverter( |
| 25 | + 'http://www.w3.org/2001/XMLSchema', |
| 26 | + 'anyXml', |
| 27 | + new class implements |
| 28 | + ElementAware, |
| 29 | + XmlEncoder { |
| 30 | + public function iso(Context $context): Iso |
| 31 | + { |
| 32 | + if ($context->type->getMeta()->isAttribute()->unwrapOr(false)) { |
| 33 | + return (new ScalarTypeEncoder())->iso($context); |
| 34 | + } |
| 35 | + |
| 36 | + $targetElementName = $context->type->getXmlTargetNodeName(); |
| 37 | + return new Iso( |
| 38 | + to: static fn (array $data): string => document_encode([$targetElementName => $data]) |
| 39 | + ->manipulate(static fn (\DOMDocument $document) => $document->documentElement->setAttributeNS( |
| 40 | + VeeWee\Xml\Xmlns\Xmlns::xsi()->value(), |
| 41 | + 'xsi:type', |
| 42 | + 'custom:type' |
| 43 | + )) |
| 44 | + ->stringifyDocumentElement(), |
| 45 | + from: static fn (string $xml): array => xml_decode($xml)[$targetElementName], |
| 46 | + ); |
| 47 | + } |
| 48 | + } |
| 49 | + ); |
0 commit comments