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