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 DirectChildElementMatcher extends TypeSafeDiagnosingMatcher { |
||
10 | |||
11 | /** |
||
12 | * @var Matcher |
||
13 | */ |
||
14 | private $matcher; |
||
15 | |||
16 | public static function havingDirectChild( 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 | 4 | public function describeTo( Description $description ) { |
|
26 | 4 | $description->appendText( 'having direct child ' ); |
|
27 | 4 | if ( $this->matcher ) { |
|
28 | 4 | $description->appendDescriptionOf( $this->matcher ); |
|
29 | 4 | } |
|
30 | 4 | } |
|
31 | |||
32 | /** |
||
33 | * @param \DOMDocument|\DOMNode $item |
||
34 | * @param Description $mismatchDescription |
||
35 | * |
||
36 | * @return bool |
||
37 | */ |
||
38 | 6 | protected function matchesSafelyWithDiagnosticDescription( $item, Description $mismatchDescription ) { |
|
39 | 6 | View Code Duplication | if ( $item instanceof \DOMDocument ) { |
0 ignored issues
–
show
|
|||
40 | 6 | $directChildren = iterator_to_array( $item->documentElement->childNodes ); |
|
41 | |||
42 | 6 | $body = array_shift( $directChildren ); |
|
43 | 6 | $directChildren = $body->childNodes; |
|
44 | 6 | } else { |
|
45 | 3 | $directChildren = $item->childNodes; |
|
46 | } |
||
47 | |||
48 | 6 | if ( $directChildren->length === 0 ) { |
|
49 | 1 | $mismatchDescription->appendText( 'with no direct children' ); |
|
50 | 1 | return false; |
|
51 | } |
||
52 | |||
53 | 6 | $childWord = $directChildren->length === 1 ? 'child' : 'children'; |
|
54 | |||
55 | 6 | $mismatchDescription->appendText( "with direct {$childWord} " ); |
|
56 | |||
57 | 6 | if ( !$this->matcher ) { |
|
58 | 1 | return count( $directChildren ) !== 0; |
|
59 | } |
||
60 | |||
61 | 5 | foreach ( $directChildren as $child ) { |
|
62 | 5 | if ( $this->matcher && $this->matcher->matches( $child ) ) { |
|
63 | 1 | return true; |
|
64 | } |
||
65 | 4 | } |
|
66 | |||
67 | 4 | $this->matcher->describeMismatch( $child, $mismatchDescription ); |
|
68 | |||
69 | 4 | return false; |
|
70 | } |
||
71 | |||
72 | } |
||
73 |
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.