gwa /dom-inspector
提供用于检查HTML标记中节点的功能。
v0.3.0
2015-10-24 07:09 UTC
Requires (Dev)
- phpunit/phpunit: ~4.4
This package is not auto-updated.
Last update: 2024-09-14 18:47:23 UTC
README
PHP >= 5.4
DOMInspector提供用于遍历和检查HTML标记中节点的PHP方法。
安装
使用composer
安装
composer require gwa/dom-inspector
示例用法
考虑以下变量$markup
中的标记
<select name="fruit" class="big"> <option value="1">apples</option> <option value="2" selected>oranges</option> <option value="3">pears</option> <option value="4">kiwis</option> </select>
在我们的单元测试中,我们想要检查HTML的结构。
// Create an Inspector instance, passing the markup. $inspector = new \Gwa\DOMInspector\Inspector($markup);
检查器代表一个包含传入的标记中节点的节点。
我们期望应该有一个单一的子节点,即select
元素。
// (We are using the PHPUnit test framework.) // Test that there is one node $this->assertEquals(1, $inspector->children()->count()); $select = $inspector->children()->get(0); // Test the "tag name" of the first node $this->assertEquals('select', $select->tagname()); // Test that the select has the class `big` $this->assertTrue($select->hasClass('big')); // Test the `name` attribute value $this->assertEquals('fruit', $select->attr('name'));
select
元素应该暴露四个option
节点。
$this->assertTrue($select->contains(4, 'option')); $this->assertEquals(4, $select->children()->count());
选择器
选择器是一个字符串,具有以下格式之一
tag
.classname
#id
tag.classname
tag#id
tag#id.classname
方法
检查器 / 节点
find($selector) NodeList
返回一个包含所有匹配选择器的子节点的NodeList
。
children($selector = null) NodeList
返回一个包含所有直接子节点的NodeList
,如果指定了数字索引,则返回单个Node
,或者如果传递了选择器字符串,则返回过滤后的节点。
// return NodeList containing all LIs $inspector->find('ul')->children(); // return NodeList containing second LI $inspector->find('ul')->children(1); // return NodeList containing all LIs with class 'active' $inspector->find('ul')->children('.active');
tagname() string
返回节点的标签名。
id() string|null
返回节点的id属性值。
attr($attr) string|null
返回节点属性的值。
html() string
返回节点的"外部"HTML值。
text() string
返回节点的文本值。
对于复杂的文本结构(例如p
和br
),会保持结构。例如,以下标记
<article>
<p>
This is some <strong>text</strong> with <em>inline styles</em>
and a <a href="http://www.example.com">link</a>.<BR/>
With a line break.
</p>
<p>
A second paragraph.
</p>
</article>
的text
方法
$inspector->children('article')->first()->text();
返回
This is some text with inline styles and a link.
With a line break.
A second paragraph.
hasClass($cssclass) boolean
断言节点是否具有作为属性的传递的类。
contains($selector) boolean
断言节点是否有一个或多个匹配选择器的直接子节点。
containsDeep($selector) boolean
断言节点是否包含一个或多个匹配选择器的子节点。
containsNum($selector) boolean
断言节点是否具有一定数量的匹配选择器的直接子节点。
containsNumDeep($selector) boolean
断言节点是否包含一定数量的匹配选择器的子节点。
NodeList
NodeList
是一个扁平列表的节点。它是可迭代的,因此您可以这样做
$blanks = []; $links = $inspector->find('a'); foreach ($links as $link) { if ($link->attr('target') === '_blank') { $blanks[] = $link; } }
count() integer
返回列表中节点的数量。
get($index) Node
返回在零基索引指定的节点。
first() Node
返回列表中的第一个节点。
last() Node
返回列表中的最后一个节点。
filter() NodeList
返回一个新创建的NodeList
,该列表通过使用传递的选择器过滤当前列表。
测试
使用phpunit
运行测试。
$ vendor/bin/phpunit -c tests/phpunit.xml tests