<?php

namespace Helpers\Outil;

class Document
{
    
    public static function getUrlDocument($urlDoc)
    {
        if (substr($urlDoc, 0, 1) == '%') {
            $positionDuDeuxieme = strpos(substr($urlDoc, 1), '%');
            $clef = substr($urlDoc, 1, $positionDuDeuxieme);
            $urlDoc = str_replace('%'.$clef.'%', $_SESSION[$clef], $urlDoc);
        }
    }
   
    public static function removeAllNamespaces(\DOMDocument $domSource): \DOMDocument
    {
        $dom = new \DOMDocument();
        $dom->formatOutput = true;
       
        $domSource = clone $domSource;
        $domSource->formatOutput = true;

        $dom->loadXML(preg_replace('/\sxmlns="(.*?)"/', '', $domSource->saveXML()));
        $xpath = new \DOMXPath($dom);

        foreach ($xpath->query('//namespace::*') as $namespaceNode) {
            $prefix = str_replace('xmlns:', '', $namespaceNode->nodeName);
            $nodes = $xpath->query("//*[namespace::{$prefix}]");

            /** @var $node @DOMElement */
            foreach ($nodes as $node) {
                $namespaceUri = $node->lookupNamespaceURI($prefix);
                $node->removeAttributeNS($namespaceUri, $prefix);
            }
        }

        $dom->loadXML($dom->saveXML());

        return $dom;
    }
}
