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
|
|
|
|