Validator   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
c 1
b 0
f 0
dl 0
loc 54
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 20 4
A isXML() 0 17 4
1
<?php
2
namespace Eduardokum\CorreiosPhp;
3
4
class Validator
5
{
6
7
    /**
8
     * @param $xml
9
     * @param $xsd
10
     *
11
     * @return bool
12
     * @throws \Exception
13
     */
14
    public static function isValid($xml, $xsd)
15
    {
16
        if (!self::isXML($xml)) {
17
            throw new \Exception('XML invalid');
18
        }
19
        libxml_use_internal_errors(true);
20
        libxml_clear_errors();
21
        $dom = new \DOMDocument('1.0', 'utf-8');
22
        $dom->preserveWhiteSpace = false;
23
        $dom->formatOutput = false;
24
        $dom->loadXML($xml, LIBXML_NOBLANKS | LIBXML_NOEMPTYTAG);
25
        libxml_clear_errors();
26
        if (! $dom->schemaValidate($xsd)) {
27
            $errors = [];
28
            foreach (libxml_get_errors() as $error) {
29
                $errors[] = $error->message;
30
            }
31
            throw new \Exception('Errors found: ' . implode(', ', $errors));
32
        }
33
        return true;
34
    }
35
36
    /**
37
     * @param $content
38
     *
39
     * @return bool
40
     */
41
    public static function isXML($content)
42
    {
43
        $content = trim($content);
44
        if (empty($content)) {
45
            return false;
46
        }
47
        if (stripos($content, '<!DOCTYPE html>') !== false
48
            || stripos($content, '</html>') !== false
49
        ) {
50
            return false;
51
        }
52
        libxml_use_internal_errors(true);
53
        libxml_clear_errors();
54
        simplexml_load_string($content, \SimpleXMLElement::class, LIBXML_NOCDATA);
55
        $errors = libxml_get_errors();
56
        libxml_clear_errors();
57
        return empty($errors);
58
    }
59
}