Passed
Push — master ( f8574f...0e1b55 )
by Julien
08:17 queued 05:08
created

MatchesSchema::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 2
c 1
b 0
f 1
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php declare(strict_types=1);
2
3
4
namespace Pitchart\Phlunit\Constraint\Xml;
5
6
use LSS\Array2XML;
7
use PHPUnit\Framework\Constraint\Constraint;
8
use Pitchart\Phlunit\Validator\ValidationError;
9
use Pitchart\Phlunit\Validator\XmlSchemaValidator;
10
11
class MatchesSchema extends Constraint
12
{
13
    /**
14
     * @var \DOMDocument
15
     */
16
    private $xsd;
17
18
    /**
19
     * @var XmlSchemaValidator
20
     */
21
    private $validator;
22
23
    /**
24
     * MatchesSchema constructor.
25
     *
26
     * @param string|\DOMDocument $xsd
27
     */
28 12
    public function __construct($xsd)
29
    {
30 12
        $this->xsd = $this->asDomDocument($xsd);
31 12
        $this->validator = new XmlSchemaValidator($xsd);
32 12
    }
33
34 10
    protected function matches($other): bool
35
    {
36 10
        return $this->validator->validate($this->asDomDocument($other));
37
    }
38
39
    /**
40
     * @param string|\DOMDocument $schema
41
     *
42
     * @return \DOMDocument
43
     */
44 12
    private function asDomDocument($schema): \DOMDocument
45
    {
46 12
        if (\is_string($schema) && \file_exists($schema) && \is_file($schema)) {
47 2
            return XmlUtility::loadFile($schema);
48
        }
49 12
        if (\is_array($schema)) {
0 ignored issues
show
introduced by
The condition is_array($schema) is always false.
Loading history...
50 3
            $schema = Array2XML::createXML('root', $schema);
51
        }
52 12
        return  XmlUtility::load($schema);
53
    }
54
55 1
    public function toString(): string
56
    {
57 1
        return 'matches xsd schema ' . $this->xsd->saveXML() . " because:\n"
58 1
            . \implode("\n", \array_map(function(ValidationError $error) {
59 1
                return $error->getMessage();
60 1
            }, $this->validator->getErrors()));
61
    }
62
63 1
    protected function failureDescription($other): string
64
    {
65 1
        $other = $this->exporter()->export($this->asDomDocument($other)->saveXML());
66 1
        $other = \preg_replace("/\n+/", "\n", $other);
67 1
        return  $other . ' ' . $this->toString();
68
    }
69
}
70