Utils::getDOMDocument()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 1
dl 0
loc 16
ccs 11
cts 11
cp 1
crap 2
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WsdlToPhp\PackageBase;
6
7
use DOMDocument;
8
use Exception;
9
use InvalidArgumentException;
10
use ValueError;
11
12
class Utils
13
{
14
    /**
15
     * Returns a XML string content as a DOMDocument or as a formated XML string
16
     * @throws InvalidArgumentException
17
     * @param string|null $string
18
     * @param bool $asDomDocument
19
     * @return DOMDocument|string|null
20
     */
21 22
    public static function getFormattedXml(?string $string, bool $asDomDocument = false)
22
    {
23 22
        if (!is_null($string)) {
24 18
            $domDocument = self::getDOMDocument($string);
25
26 12
            return $asDomDocument ? $domDocument : $domDocument->saveXML();
27
        }
28
29 4
        return null;
30
    }
31
32
    /**
33
     * @param string $string
34
     * @return DOMDocument
35
     * @throws InvalidArgumentException|ValueError
36
     */
37 22
    public static function getDOMDocument(string $string): DOMDocument
38
    {
39 22
        $dom = new DOMDocument('1.0', 'UTF-8');
40 22
        $dom->formatOutput = true;
41 22
        $dom->preserveWhiteSpace = false;
42 22
        $dom->resolveExternals = false;
43 22
        $dom->substituteEntities = false;
44 22
        $dom->validateOnParse = false;
45
46
        try {
47 22
            $dom->loadXML($string);
48 8
        } catch (Exception $exception) {
49 5
            throw new InvalidArgumentException('XML string is invalid', $exception->getCode(), $exception);
50
        }
51
52 14
        return $dom;
53
    }
54
}
55