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
![]() |
|||
50 | 3 | $schema = Array2XML::createXML('root', $schema); |
|
51 | } |
||
52 | 12 | return XmlUtility::load($schema); |
|
53 | } |
||
54 | |||
55 | /** |
||
56 | * @return string |
||
57 | */ |
||
58 | 1 | public function toString(): string |
|
59 | { |
||
60 | 1 | return 'matches xsd schema ' . $this->xsd->saveXML() . " because:\n" |
|
61 | 1 | . \implode("\n", \array_map(function(ValidationError $error) { |
|
62 | 1 | return $error->getMessage(); |
|
63 | 1 | }, $this->validator->getErrors())); |
|
64 | } |
||
65 | |||
66 | /** |
||
67 | * @return string |
||
68 | */ |
||
69 | 1 | protected function failureDescription($other): string |
|
70 | { |
||
71 | 1 | $other = $this->exporter()->export($this->asDomDocument($other)->saveXML()); |
|
72 | 1 | $other = \preg_replace("/\n+/", "\n", $other); |
|
73 | 1 | return $other . ' ' . $this->toString(); |
|
74 | } |
||
75 | } |
||
76 |