XmlStringFormatter::isXmlString()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
rs 9.2
cc 4
eloc 9
nc 4
nop 1
1
<?php
2
3
namespace Glooby\Debug\Formatter;
4
5
use Glooby\Debug\Exception\FormatterException;
6
7
/**
8
 * @author Emil Kilhage
9
 */
10
class XmlStringFormatter implements FormatterInterface
11
{
12
    /**
13
     * @var array
14
     */
15
    private static $headers = [
16
        '/^application\/.*xml/',
17
    ];
18
19
    /**
20
     * @param string $header
21
     * @return bool
22
     */
23
    public static function isXmlHeader($header)
24
    {
25
        foreach (self::$headers as $pattern) {
26
            if (preg_match($pattern, $header)) {
27
                return true;
28
            }
29
        }
30
31
        return false;
32
    }
33
34
    /**
35
     * @param string $string
36
     * @return bool
37
     */
38
    public static function isXmlString($string)
39
    {
40
        $string = trim($string);
41
42
        if (substr($string, 0, 1) === '<' && substr($string, -1, 1) === '>') {
43
            try {
44
                $dom = new \DOMDocument('1.0');
45
                $dom->validateOnParse = true;
46
                return $dom->loadXML($string) !== false;
47
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
48
49
            }
50
        }
51
52
        return false;
53
    }
54
55
    /**
56
     * @param string $xml
57
     * @return string
58
     * @throws FormatterException
59
     */
60
    public function format($xml)
61
    {
62
        try {
63
            $dom = new \DOMDocument('1.0');
64
            $dom->preserveWhiteSpace = false;
65
            $dom->formatOutput = true;
66
            $dom->validateOnParse = true;
67
            $dom->loadXML($xml);
68
            return $dom->saveXML();
69
        } catch (\Exception $e) {
70
            return $xml;
71
        }
72
    }
73
}
74