AttributeMatcher   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 66.67%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 4
dl 0
loc 79
ccs 20
cts 30
cp 0.6667
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A withAttribute() 0 3 1
A __construct() 0 5 1
A havingValue() 0 7 1
A describeTo() 0 8 2
A matchesSafelyWithDiagnosticDescription() 0 19 6
1
<?php
2
3
namespace WMDE\HamcrestHtml;
4
5
use Hamcrest\Description;
6
use Hamcrest\Matcher;
7
use Hamcrest\Util;
8
9
class AttributeMatcher extends TagMatcher {
10
11
	/**
12
	 * @var Matcher
13
	 */
14
	private $attributeNameMatcher;
15
16
	/**
17
	 * @var Matcher|null
18
	 */
19
	private $valueMatcher;
20
21
	/**
22
	 * @param Matcher|string $attributeName
23
	 *
24
	 * @return self
25
	 */
26
	public static function withAttribute( $attributeName ) {
27
		return new static( Util::wrapValueWithIsEqual( $attributeName ) );
28
	}
29
30
	/**
31
	 * @param Matcher $attributeNameMatcher
32
	 */
33
	public function __construct( Matcher $attributeNameMatcher ) {
34
		parent::__construct();
35
36
		$this->attributeNameMatcher = $attributeNameMatcher;
37
	}
38
39
	/**
40
	 * @param Matcher|string $value
41
	 *
42
	 * @return AttributeMatcher
43
	 */
44
	public function havingValue( $value ) {
45
		// TODO: Throw exception if value is set
46
		$result = clone $this;
47
		$result->valueMatcher = Util::wrapValueWithIsEqual( $value );
48
49
		return $result;
50
	}
51
52 2
	public function describeTo( Description $description ) {
53 2
		$description->appendText( 'with attribute ' )
54 2
			->appendDescriptionOf( $this->attributeNameMatcher );
55 2
		if ( $this->valueMatcher ) {
56 1
			$description->appendText( ' having value ' )
57 1
				->appendDescriptionOf( $this->valueMatcher );
58 1
		}
59 2
	}
60
61
	/**
62
	 * @param \DOMElement $item
63
	 * @param Description $mismatchDescription
64
	 *
65
	 * @return bool
66
	 */
67 6
	protected function matchesSafelyWithDiagnosticDescription( $item, Description $mismatchDescription ) {
68
		/** @var \DOMAttr $attribute */
69 6
		foreach ( $item->attributes as $attribute ) {
70 6
			if ( $this->valueMatcher ) {
71
				if (
72 4
					$this->attributeNameMatcher->matches( $attribute->name )
73 4
					&& $this->valueMatcher->matches( $attribute->value )
74 4
				) {
75 2
					return true;
76
				}
77 3
			} else {
78 2
				if ( $this->attributeNameMatcher->matches( $attribute->name ) ) {
79 1
					return true;
80
				}
81
			}
82 6
		}
83
84 5
		return false;
85
	}
86
87
}
88