1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
namespace Codeception\Util;
use Codeception\Exception\ElementNotFound;
use Codeception\Exception\MalformedLocatorException;
use Symfony\Component\CssSelector\CssSelectorConverter;
use Symfony\Component\CssSelector\Exception\ParseException;
use Codeception\Util\Soap as XmlUtils;
class XmlStructure
{
/**
* @var \DOMDocument|\DOMNode
*/
protected $xml;
public function __construct($xml)
{
$this->xml = XmlUtils::toXml($xml);
}
public function matchesXpath($xpath)
{
$path = new \DOMXPath($this->xml);
$res = $path->query($xpath);
if ($res === false) {
throw new MalformedLocatorException($xpath);
}
return $res->length > 0;
}
/**
* @param $cssOrXPath
* @return \DOMElement
*/
public function matchElement($cssOrXPath)
{
$xpath = new \DOMXpath($this->xml);
try {
$selector = (new CssSelectorConverter())->toXPath($cssOrXPath);
$els = $xpath->query($selector);
if ($els) {
return $els->item(0);
}
} catch (ParseException $e) {
}
$els = $xpath->query($cssOrXPath);
if ($els->length) {
return $els->item(0);
}
throw new ElementNotFound($cssOrXPath);
}
/**
* @param $xml
* @return bool
*/
public function matchXmlStructure($xml)
{
$xml = XmlUtils::toXml($xml);
$root = $xml->firstChild;
$els = $this->xml->getElementsByTagName($root->nodeName);
if (empty($els)) {
throw new ElementNotFound($root->nodeName, 'Element');
}
$matches = false;
foreach ($els as $node) {
$matches |= $this->matchForNode($root, $node);
}
return $matches;
}
protected function matchForNode($schema, $xml)
{
foreach ($schema->childNodes as $node1) {
$matched = false;
foreach ($xml->childNodes as $node2) {
if ($node1->nodeName == $node2->nodeName) {
$matched = $this->matchForNode($node1, $node2);
if ($matched) {
break;
}
}
}
if (!$matched) {
return false;
}
}
return true;
}
}