Passed
Push — develop ( de55f2...b27c00 )
by Mikaël
48:31 queued 02:41
created

Utils::getFormattedXml()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

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