public static function replaceReferences($request)
    {
        $requestDom = new DOMDocument();
        try {
            set_error_handler([self::class, 'handleLoadXmlWarnings']);
            $requestDom->loadXML($request);
        } catch (DOMException $e) {
            return $request;
        } finally {
            restore_error_handler();
        }

        $xpath = new DOMXPath($requestDom);
        $references = $xpath->query('//*[@href]');
        // Cache of referenced element IDs to their nodes.
        $referencedElementsCache = [];

        // Replace each reference.
        foreach ($references as $reference) {
            // References begin with a hash, e,g., #ref1, remove the hash sign.
            $id = substr($reference->getAttribute('href'), 1);

            // If we haven't seen this referenced node before we need to find it and
            // cache it.
            if (!array_key_exists($id, $referencedElementsCache)) {
                $referencedElements = $xpath->query(sprintf("//*[@id='%s']", $id));
                // There may be more than one element with the same ID if we replaced
                // a reference to an element that has a child node that something else
                // is referencing.
                if ($referencedElements->length > 0) {
                    $referencedElementsCache[$id] = $referencedElements->item(0);
                } else {
                    // If for some reason we can't find it, it's probably a malformed SOAP
                    // request XML and we skip this reference so the issue bubbles up.
                    continue;
                }
            }

            // Deep copy all the nodes from the referenced element.
            foreach ($referencedElementsCache[$id]->childNodes as $childNode) {
                $reference->appendChild($childNode->cloneNode(true));
            }
            $reference->removeAttribute('href');
        }

        // Once all references are replaced, remove the obsolete ID tags from each
        // referenced element.
        foreach (array_keys($referencedElementsCache) as $id) {
            // For the same reason stated above, there may be more than one element
            // with the same ID due to replacement.
            $referencedElements = $xpath->query(sprintf("//*[@id='%s']", $id));
            foreach ($referencedElements as $referencedElement) {
                $referencedElement->removeAttribute('id');
            }
        }

        return $requestDom->saveXML();
    }