-
Notifications
You must be signed in to change notification settings - Fork 1
/
ChildElementMatcher.php
67 lines (53 loc) · 1.61 KB
/
ChildElementMatcher.php
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
<?php
namespace WMDE\HamcrestHtml;
use Hamcrest\Description;
use Hamcrest\Matcher;
use Hamcrest\TypeSafeDiagnosingMatcher;
class ChildElementMatcher extends TypeSafeDiagnosingMatcher {
/**
* @var Matcher|null
*/
private $matcher;
public static function havingChild( Matcher $elementMatcher = null ) {
return new static( $elementMatcher );
}
public function __construct( Matcher $matcher = null ) {
parent::__construct( \DOMNode::class );
$this->matcher = $matcher;
}
public function describeTo( Description $description ) {
$description->appendText( 'having child ' );
if ( $this->matcher ) {
$description->appendDescriptionOf( $this->matcher );
}
}
/**
* @param \DOMDocument|\DOMNode $item
* @param Description $mismatchDescription
*
* @return bool
*/
protected function matchesSafelyWithDiagnosticDescription( $item, Description $mismatchDescription ) {
if ( $item instanceof \DOMDocument ) {
$directChildren = iterator_to_array( $item->documentElement->childNodes );
$body = array_shift( $directChildren );
$directChildren = $body->childNodes;
} else {
$directChildren = $item->childNodes;
}
if ( $directChildren->length === 0 ) {
$mismatchDescription->appendText( 'having no children' );
return false;
}
if ( !$this->matcher ) {
return $directChildren->length > 0;
}
foreach ( new XmlNodeRecursiveIterator( $directChildren ) as $child ) {
if ( $this->matcher && $this->matcher->matches( $child ) ) {
return true;
}
}
$mismatchDescription->appendText( 'having no children ' )->appendDescriptionOf( $this->matcher );
return false;
}
}