|
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)) { |
|
|
|
|
|
|
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
|
|
|
|