forked from php-soap/encoding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocumentToLookupArrayReader.php
More file actions
69 lines (59 loc) · 2.15 KB
/
DocumentToLookupArrayReader.php
File metadata and controls
69 lines (59 loc) · 2.15 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
<?php
declare(strict_types=1);
namespace Soap\Encoding\Xml\Reader;
use Dom\Attr;
use Dom\Node;
use Soap\Encoding\Xml\Node\Element;
use Soap\Encoding\Xml\Node\ElementList;
use VeeWee\Xml\Xmlns\Xmlns;
use function VeeWee\Xml\Dom\Predicate\is_element;
/**
* @psalm-type LookupArrayValue = string|Element|ElementList
* @psalm-type LookupArray = array<string, LookupArrayValue>
*/
final class DocumentToLookupArrayReader
{
/**
* @return LookupArray
*/
public function __invoke(Element $xml): array
{
$root = $xml->element();
/** @var LookupArray $nodes */
$nodes = [];
// Read all child elements.
// The key is the name of the elements
// The value is the raw XML for those element(s)
/** @var iterable<Node> $children */
$children = $root->childNodes;
foreach ($children as $element) {
if (!is_element($element)) {
continue;
}
$key = $element->localName;
$previousValue = $nodes[$key] ?? null;
$currentElement = Element::fromDOMElement($element);
// Incrementally build up lists.
/** @var LookupArrayValue $value */
$value = match(true) {
$previousValue instanceof ElementList => $previousValue->append($currentElement),
$previousValue instanceof Element => new ElementList($previousValue, $currentElement),
default => $currentElement
};
$nodes[$key] = $value;
}
// It might be possible that the child is a regular textNode.
// In that case, we use '_' as the key and the value of the textNode as value.
if (!$nodes && $root->getAttributeNS(Xmlns::xsi()->value(), 'nil') !== 'true') {
$nodes['_'] = $root->textContent ?? '';
}
// All attributes also need to be added as key => value pairs.
/** @var \iterable<Attr> $attributes */
$attributes = $root->attributes;
foreach ($attributes as $attribute) {
$key = $attribute->localName;
$nodes[$key] = $attribute->value;
}
return $nodes;
}
}