Passed
Push — master ( 0cd9de...ba1253 )
by Tim
02:15
created

AbstractSerializableXML::isEmptyElement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML;
6
7
use DOMElement;
8
use SimpleSAML\XML\DOMDocumentFactory;
9
use Serializable;
10
11
use function get_object_vars;
12
13
/**
14
 * Abstract class for serialization of XML structures
15
 *
16
 * @package simplesamlphp/xml-common
17
 */
18
abstract class AbstractSerializableXML implements XMLElementInterface, Serializable
19
{
20
    /**
21
     * Whether to format the string output of this element or not.
22
     *
23
     * Defaults to true. Override to disable output formatting.
24
     *
25
     * @var bool
26
     */
27
    protected bool $formatOutput = true;
28
29
30
    /**
31
     * Output the class as an XML-formatted string
32
     *
33
     * @return string
34
     */
35
    public function __toString(): string
36
    {
37
        $xml = $this->toXML();
38
        /** @psalm-var \DOMDocument $xml->ownerDocument */
39
        $xml->ownerDocument->formatOutput = $this->formatOutput;
40
        return $xml->ownerDocument->saveXML($xml);
41
    }
42
43
44
    /**
45
     * Serialize this XML chunk
46
     *
47
     * @return string The serialized chunk.
48
     */
49
    public function serialize(): string
50
    {
51
        $xml = $this->toXML();
52
        /** @psalm-var \DOMDocument $xml->ownerDocument */
53
        return $xml->ownerDocument->saveXML($xml);
54
    }
55
56
57
    /**
58
     * Un-serialize this XML chunk.
59
     *
60
     * @param string $serialized The serialized chunk.
61
     *
62
     * Type hint not possible due to upstream method signature
63
     */
64
    public function unserialize($serialized): void
65
    {
66
        $doc = DOMDocumentFactory::fromString($serialized);
67
        $obj = static::fromXML($doc->documentElement);
68
69
        // For this to work, the properties have to be protected
70
        foreach (get_object_vars($obj) as $property => $value) {
71
            $this->{$property} = $value;
72
        }
73
    }
74
75
76
    /**
77
     * Test if an object, at the state it's in, would produce an empty XML-element
78
     *
79
     * @return bool
80
     */
81
    abstract public function isEmptyElement(): bool;
82
83
84
    /**
85
     * Create a class from XML
86
     *
87
     * @param \DOMElement $xml
88
     * @return self
89
     */
90
    abstract public static function fromXML(DOMElement $xml): object;
91
92
93
    /**
94
     * Create XML from this class
95
     *
96
     * @param \DOMElement|null $parent
97
     * @return \DOMElement
98
     */
99
    abstract public function toXML(DOMElement $parent = null): DOMElement;
100
}
101