Passed
Push — master ( 771255...d0c763 )
by Marius
01:01 queued 10s
created

matchesSafelyWithDiagnosticDescription()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6.0087

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 10
nop 2
dl 0
loc 25
ccs 15
cts 16
cp 0.9375
crap 6.0087
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace WMDE\HamcrestHtml;
4
5
use Hamcrest\Description;
6
use Hamcrest\Matcher;
7
use Hamcrest\TypeSafeDiagnosingMatcher;
8
9
class ChildElementMatcher extends TypeSafeDiagnosingMatcher {
10
11
	/**
12
	 * @var Matcher|null
13
	 */
14
	private $matcher;
15
16
	public static function havingChild( Matcher $elementMatcher = null ) {
17
		return new static( $elementMatcher );
18
	}
19
20
	public function __construct( Matcher $matcher = null ) {
21
		parent::__construct( \DOMNode::class );
22
		$this->matcher = $matcher;
23
	}
24
25 7
	public function describeTo( Description $description ) {
26 7
		$description->appendText( 'having child ' );
27 7
		if ( $this->matcher ) {
28 6
			$description->appendDescriptionOf( $this->matcher );
29 6
		}
30 7
	}
31
32
	/**
33
	 * @param \DOMDocument|\DOMNode $item
34
	 * @param Description $mismatchDescription
35
	 *
36
	 * @return bool
37
	 */
38 17
	protected function matchesSafelyWithDiagnosticDescription( $item, Description $mismatchDescription ) {
39 17
		if ( $item instanceof \DOMDocument ) {
40 16
			$directChildren = $item->documentElement->childNodes->item( 0 )->childNodes;
41 16
		} else {
42 1
			$directChildren = $item->childNodes;
43
		}
44
45 17
		if ( $directChildren->length === 0 ) {
46 1
			$mismatchDescription->appendText( 'having no children' );
47 1
			return false;
48
		}
49
50 16
		if ( !$this->matcher ) {
51
			return $directChildren->length > 0;
52
		}
53
54 16
		foreach ( new XmlNodeRecursiveIterator( $directChildren ) as $child ) {
55 16
			if ( $this->matcher->matches( $child ) ) {
56 10
				return true;
57
			}
58 11
		}
59
60 6
		$mismatchDescription->appendText( 'having no children ' )->appendDescriptionOf( $this->matcher );
61 6
		return false;
62
	}
63
64
}
65