|
5 | 5 | namespace SimpleSAML\XML; |
6 | 6 |
|
7 | 7 | use DOMDocument; |
| 8 | +use DOMElement; |
| 9 | +use DOMXPath; |
8 | 10 | use SimpleSAML\XML\Assert\Assert; |
9 | 11 | use SimpleSAML\XML\Exception\IOException; |
10 | 12 | use SimpleSAML\XML\Exception\RuntimeException; |
11 | 13 | use SimpleSAML\XML\Exception\UnparseableXMLException; |
12 | 14 |
|
| 15 | +use function count; |
13 | 16 | use function file_get_contents; |
14 | 17 | use function func_num_args; |
15 | 18 | use function libxml_clear_errors; |
16 | 19 | use function libxml_set_external_entity_loader; |
17 | 20 | use function libxml_use_internal_errors; |
18 | 21 | use function sprintf; |
| 22 | +use function strpos; |
| 23 | +use function substr; |
19 | 24 |
|
20 | 25 | /** |
21 | 26 | * @package simplesamlphp/xml-common |
@@ -115,4 +120,48 @@ public static function create(string $version = '1.0', string $encoding = 'UTF-8 |
115 | 120 | { |
116 | 121 | return new DOMDocument($version, $encoding); |
117 | 122 | } |
| 123 | + |
| 124 | + |
| 125 | + public static function normalizeDocument(DOMDocument $doc): DOMDocument |
| 126 | + { |
| 127 | + // Get the root element |
| 128 | + $root = $doc->documentElement; |
| 129 | + |
| 130 | + // Collect all xmlns attributes from the document |
| 131 | + $xpath = new DOMXPath($doc); |
| 132 | + $xmlnsAttributes = []; |
| 133 | + |
| 134 | + // Register all namespaces to ensure XPath can handle them |
| 135 | + foreach ($xpath->query('//namespace::*') as $node) { |
| 136 | + $name = $node->nodeName === 'xmlns' ? 'xmlns' : $node->nodeName; |
| 137 | + $xmlnsAttributes[$name] = $node->nodeValue; |
| 138 | + } |
| 139 | + |
| 140 | + // If no xmlns attributes found, return early with debug info |
| 141 | + if (empty($xmlnsAttributes)) { |
| 142 | + return $doc->saveXML(); |
| 143 | + } |
| 144 | + |
| 145 | + // Remove xmlns attributes from all elements |
| 146 | + $nodes = $xpath->query('//*[namespace::*]'); |
| 147 | + foreach ($nodes as $node) { |
| 148 | + $attributesToRemove = []; |
| 149 | + foreach ($node->attributes as $attr) { |
| 150 | + if (strpos($attr->nodeName, 'xmlns') === 0 || $attr->nodeName === 'xmlns') { |
| 151 | + $attributesToRemove[] = $attr->nodeName; |
| 152 | + } |
| 153 | + } |
| 154 | + foreach ($attributesToRemove as $attrName) { |
| 155 | + $node->removeAttribute($attrName); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + // Add all collected xmlns attributes to the root element |
| 160 | + foreach ($xmlnsAttributes as $name => $value) { |
| 161 | + $root->setAttribute($name, $value); |
| 162 | + } |
| 163 | + |
| 164 | + // Return the normalized XML |
| 165 | + return static::fromString($root->ownerDocument->saveXML()); |
| 166 | + } |
118 | 167 | } |
0 commit comments