public static function toDOMDocument($xml)
    {
        if ($xml instanceof \DOMDocument) {
            return $xml;
        }

        if ($xml instanceof \SimpleXMLElement) {
            $doc = new \DOMDocument();
            $doc->loadXML('' . $xml->asXML());

            return $doc;
        }

        if (is_string($xml)) {
            $doc = new \DOMDocument();

            if (is_file($xml)) {
                $doc->load($xml);

                return $doc;
            }

            $doc->loadXML($xml);

            return $doc;
        }

        $type = is_object($xml) ? get_class($xml) : gettype($xml);

        throw new \InvalidArgumentException("Cannot convert instance of '$type' to DOMDocument");
    }