Passed
Push — master ( bec514...029453 )
by Tim
01:50
created

ExtendableElementTrait::toXML()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML;
6
7
use DOMElement;
8
use SimpleSAML\Assert\Assert;
9
10
/**
11
 * Trait grouping common functionality for elements implementing the xs:any element.
12
 *
13
 * @package simplesamlphp/xml-common
14
 */
15
trait ExtendableElementTrait
16
{
17
    /** @var \SimpleSAML\XML\XMLElementInterface[] */
18
    protected array $extensions = [];
19
20
21
    /**
22
     * Extensions constructor.
23
     *
24
     * @var \SimpleSAML\XML\XMLElementInterface[]
25
     */
26
    public function __construct(array $extensions)
27
    {
28
        $this->setList($extensions);
29
    }
30
31
32
    /**
33
     * Set an array with all extensions present.
34
     *
35
     * @param array \SimpleSAML\XML\XMLElementInterface[]
36
     */
37
    public function setList(array $extensions): void
38
    {
39
        Assert::allIsInstanceOf($extensions, XMLElementInterface::class);
40
41
        $this->extensions = $extensions;
42
    }
43
44
45
    /**
46
     * Get an array with all extensions present.
47
     *
48
     * @return \SimpleSAML\XML\XMLElementInterface[]
49
     */
50
    public function getList(): array
51
    {
52
        return $this->extensions;
53
    }
54
55
56
    /**
57
     * @return bool
58
     */
59
    public function isEmptyElement(): bool
60
    {
61
        if (empty($this->extensions)) {
62
            return true;
63
        }
64
65
        $empty = false;
66
        foreach ($this->extensions as $extension) {
67
            $empty &= $extension->isEmptyElement();
68
        }
69
70
        return boolval($empty);
71
    }
72
73
74
    /**
75
     * Convert this object into its md:Extensions XML representation.
76
     *
77
     * @param \DOMElement|null $parent The element we should add this Extensions element to.
78
     * @return \DOMElement The new md:Extensions XML element.
79
     */
80
    public function toXML(DOMElement $parent = null): DOMElement
81
    {
82
        $e = $this->instantiateParentElement($parent);
83
84
        foreach ($this->extensions as $extension) {
85
            if (!$extension->isEmptyElement()) {
86
                $extension->toXML($e);
87
            }
88
        }
89
90
        return $e;
91
    }
92
93
94
    /**
95
     * @param \DOMElement|null $parent
96
     * @return \DOMElement
97
     */
98
    abstract public function instantiateParentElement(DOMElement $parent = null): DOMElement;
99
}
100