Passed
Push — master ( 0e0de3...cb02e9 )
by Gabriel
03:02
created

Xml::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 10
c 1
b 0
f 1
dl 0
loc 16
rs 9.9332
cc 3
nc 3
nop 2
1
<?php
2
/** @noinspection PhpComposerExtensionStubsInspection */
3
4
namespace Nip\Utility;
5
6
/**
7
 * Class Xml
8
 * @package Nip\Utility
9
 */
10
class Xml
11
{
12
    /**
13
     * @param $xml
14
     * @param $schema
15
     *
16
     * @throws \Exception
17
     */
18
    public static function validate($xml, $schema)
19
    {
20
        libxml_use_internal_errors(true);
21
        $xmlDocument = new \DOMDocument();
22
        $xmlDocument->loadXML($xml);
23
24
        $schema = static::prepareSchema($schema);
25
26
        if (!$xmlDocument->schemaValidateSource($schema)) {
0 ignored issues
show
Bug introduced by
It seems like $schema can also be of type false; however, parameter $source of DOMDocument::schemaValidateSource() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

26
        if (!$xmlDocument->schemaValidateSource(/** @scrutinizer ignore-type */ $schema)) {
Loading history...
27
            $errors = libxml_get_errors();
28
29
            foreach ($errors as $error) {
30
                throw new \Exception(static::displayError($error));
31
            }
32
            libxml_clear_errors();
33
            throw new \Exception('INVALID XML');
34
        }
35
    }
36
37
    /**
38
     * @param $error
39
     *
40
     * @return string
41
     */
42
    public static function displayError($error): string
43
    {
44
        $return = "\n";
45
        switch ($error->level) {
46
            case LIBXML_ERR_WARNING:
47
                $return .= "Warning $error->code: ";
48
                break;
49
            case LIBXML_ERR_ERROR:
50
                $return .= "Error $error->code: ";
51
                break;
52
            case LIBXML_ERR_FATAL:
53
                $return .= "Fatal Error $error->code: ";
54
                break;
55
        }
56
        $return .= trim($error->message);
57
        $return .= "\n";
58
59
        return $return;
60
    }
61
62
    /**
63
     * @param $schema
64
     *
65
     * @return false|string
66
     */
67
    protected static function prepareSchema($schema)
68
    {
69
        if (!Url::isValid($schema)) {
70
            return $schema;
71
        }
72
        $response = file_get_contents($schema);
73
74
        return $response;
75
    }
76
}