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

src/ChildElementMatcher.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 View Code Duplication
		if ( $item instanceof \DOMDocument ) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
40 16
			$directChildren = iterator_to_array( $item->documentElement->childNodes );
41
42 16
			$body = array_shift( $directChildren );
43 16
			$directChildren = $body->childNodes;
44 16
		} else {
45 1
			$directChildren = $item->childNodes;
46
		}
47
48 17
		if ( $directChildren->length === 0 ) {
49 1
			$mismatchDescription->appendText( 'having no children' );
50 1
			return false;
51
		}
52
53 16
		if ( !$this->matcher ) {
54
			return $directChildren->length > 0;
55
		}
56
57 16
		foreach ( new XmlNodeRecursiveIterator( $directChildren ) as $child ) {
58 16
			if ( $this->matcher && $this->matcher->matches( $child ) ) {
59 10
				return true;
60
			}
61 11
		}
62
63 6
		$mismatchDescription->appendText( 'having no children ' )->appendDescriptionOf( $this->matcher );
64 6
		return false;
65
	}
66
67
}
68