|
| 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\ElementContextEnhancer; |
| 6 | +use Soap\Encoding\Encoder\SimpleType\ScalarTypeEncoder; |
| 7 | +use Soap\Encoding\Encoder\XmlEncoder; |
| 8 | +use Soap\Encoding\EncoderRegistry; |
| 9 | +use Soap\Engine\Metadata\Model\TypeMeta; |
| 10 | +use Soap\WsdlReader\Model\Definitions\BindingUse; |
| 11 | +use VeeWee\Reflecta\Iso\Iso; |
| 12 | + |
| 13 | +/** |
| 14 | + * This encoder can add xsi:type information to the XML element on xsd:anyType simpleTypes on literal encoded documents. |
| 15 | + * |
| 16 | + * <xsd:element minOccurs="0" maxOccurs="1" name="value" type="xsd:anyType" /> |
| 17 | + * |
| 18 | + * Will Result in for example: |
| 19 | + * |
| 20 | + * <value |
| 21 | + * xmlns:xsd="http://www.w3.org/2001/XMLSchema" |
| 22 | + * xsi:type="xsds:int" |
| 23 | + * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 24 | + * > |
| 25 | + * 789 |
| 26 | + * </value> |
| 27 | + */ |
| 28 | + |
| 29 | +EncoderRegistry::default() |
| 30 | + ->addSimpleTypeConverter( |
| 31 | + 'http://www.w3.org/2001/XMLSchema', |
| 32 | + 'anyType', |
| 33 | + new class implements |
| 34 | + ElementContextEnhancer, |
| 35 | + XmlEncoder { |
| 36 | + public function iso(Context $context): Iso |
| 37 | + { |
| 38 | + return (new ScalarTypeEncoder())->iso($context); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * This method allows to change the context on the wrapping elementEncoder. |
| 43 | + * By forcing the bindingUse to `ENCODED`, we can make sure the xsi:type attribute is added. |
| 44 | + * We also make sure the type is not qualified so that the xsi:type prefix xmlns is imported as well. |
| 45 | + */ |
| 46 | + public function enhanceElementContext(Context $context): Context |
| 47 | + { |
| 48 | + return $context |
| 49 | + ->withBindingUse(BindingUse::ENCODED) |
| 50 | + ->withType( |
| 51 | + $context->type->withMeta( |
| 52 | + static fn (TypeMeta $meta): TypeMeta => $meta->withIsQualified(false) |
| 53 | + ) |
| 54 | + ); |
| 55 | + } |
| 56 | + } |
| 57 | + ); |
0 commit comments