-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSerializableElementTrait.php
More file actions
92 lines (74 loc) · 2.32 KB
/
Copy pathSerializableElementTrait.php
File metadata and controls
92 lines (74 loc) · 2.32 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
namespace SimpleSAML\XML;
use DOMElement;
use SimpleSAML\XML\DOMDocumentFactory;
use function array_last;
use function get_object_vars;
/**
* Trait grouping common functionality for elements implementing the SerializableElement element.
*
* @package simplesamlphp/xml-common
*/
trait SerializableElementTrait
{
/**
* Whether to format the string output of this element or not.
*
* Defaults to true. Override to disable output formatting.
*/
protected bool $formatOutput = true;
/**
* Output the class as an XML-formatted string
*/
public function __toString(): string
{
$xml = $this->toXML();
$xmlString = $xml->ownerDocument->saveXML();
$doc = DOMDocumentFactory::fromString($xmlString);
$doc->formatOutput = $this->formatOutput;
if (static::getNormalization() === true) {
$normalized = DOMDocumentFactory::normalizeDocument($doc);
$normalized->normalizeDocument();
return $normalized->saveXML($normalized->firstChild);
}
$doc->normalizeDocument();
return $doc->saveXML($doc->firstChild);
}
/**
* Serialize this XML chunk.
*
* This method will be invoked by any calls to serialize().
*
* @return array{0: string} The serialized representation of this XML object.
*/
public function __serialize(): array
{
$xml = $this->toXML();
return [$xml->ownerDocument->saveXML($xml)];
}
/**
* Unserialize an XML object and load it..
*
* This method will be invoked by any calls to unserialize(), allowing us to restore any data that might not
* be serializable in its original form (e.g.: DOM objects).
*
* @param array{0: string} $serialized The XML object that we want to restore.
*/
public function __unserialize(array $serialized): void
{
$xml = static::fromXML(
DOMDocumentFactory::fromString(array_last($serialized))->documentElement,
);
$vars = get_object_vars($xml);
foreach ($vars as $k => $v) {
$this->$k = $v;
}
}
/**
* Create XML from this class
*
* @param \DOMElement|null $parent
*/
abstract public function toXML(?DOMElement $parent = null): DOMElement;
}