Skip to content

Commit 3d7ccad

Browse files
committed
adding hasAttribute
1 parent 9663472 commit 3d7ccad

File tree

4 files changed

+35
-3
lines changed

4 files changed

+35
-3
lines changed

src/PHPHtmlParser/Dom/AbstractNode.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,18 @@ public function getAttribute($key)
293293
return $attribute;
294294
}
295295

296+
/**
297+
* A wrapper method that simply calls the hasAttribute method
298+
* on the tag of this node.
299+
*
300+
* @param string $key
301+
* @return bool
302+
*/
303+
public function hasAttribute($key)
304+
{
305+
return $this->tag->hasAttribute($key);
306+
}
307+
296308
/**
297309
* A wrapper method that simply calls the setAttribute method
298310
* on the tag of this node.

src/PHPHtmlParser/Dom/Tag.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,17 @@ public function getAttribute($key)
225225
return $this->attr[$key];
226226
}
227227

228+
/**
229+
* Returns TRUE if node has attribute
230+
*
231+
* @param string $key
232+
* @return bool
233+
*/
234+
public function hasAttribute($key)
235+
{
236+
return isset($this->attr[$key]);
237+
}
238+
228239
/**
229240
* Generates the opening tag for this object.
230241
*

src/PHPHtmlParser/Selector.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -232,9 +232,7 @@ protected function seek(array $nodes, array $rule, array $options)
232232
$pass = false;
233233
}
234234
} else {
235-
if ($rule['key'] != 'plaintext' &&
236-
is_null($child->getAttribute($rule['key']))
237-
) {
235+
if ($rule['key'] != 'plaintext' && !$child->hasAttribute($rule['key'])) {
238236
$pass = false;
239237
}
240238
}

tests/SelectorTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,15 @@ public function testFindChildUsingChildSelector()
203203
$selector = new Selector('div > ul');
204204
$this->assertEquals(1, count($selector->find($root)));
205205
}
206+
207+
public function testFindNodeByAttributeOnly()
208+
{
209+
$root = new HtmlNode(new Tag('root'));
210+
$child1 = new HtmlNode(new Tag('ul'));
211+
$child1->setAttribute('custom-attr', null);
212+
$root->addChild($child1);
213+
214+
$selector = new Selector('[custom-attr]');
215+
$this->assertEquals(1, count($selector->find($root)));
216+
}
206217
}

0 commit comments

Comments
 (0)