Skip to content

Commit

Permalink
Merge pull request #226 from HongjiangHuang/dev/3.0.0
Browse files Browse the repository at this point in the history
[dev/3.0.0]feature: innerText property support
  • Loading branch information
paquettg authored Jul 17, 2020
2 parents c487fce + a430293 commit a2c5eb1
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/PHPHtmlParser/Dom/Node/AbstractNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ public function __get(string $key)
return $this->outerHtml();
case 'innerhtml':
return $this->innerHtml();
case 'innertext':
return $this->innerText();
case 'text':
return $this->text();
case 'tag':
Expand Down
22 changes: 22 additions & 0 deletions src/PHPHtmlParser/Dom/Node/HtmlNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ class HtmlNode extends InnerNode
*/
protected $outerHtml;

/**
* Remembers what the innerText was if it was scanned previously.
*
* @var ?string
*/
protected $innerText = null;

/**
* Remembers what the text was if it was scanned previously.
*
Expand Down Expand Up @@ -111,6 +118,21 @@ public function innerHtml(): string
return $string;
}

/**
* Gets the inner text of this node.
* @return string
* @throws ChildNotFoundException
* @throws UnknownChildTypeException
*/
public function innerText(): string
{
if (is_null($this->innerText)) {
$this->innerText = strip_tags($this->innerHtml());
}

return $this->innerText;
}

/**
* Gets the html of this node, including it's own
* tag.
Expand Down
10 changes: 10 additions & 0 deletions tests/DomTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,16 @@ public function testEmptyAttribute()
$this->assertEquals(1, \count($items));
}

public function testInnerText()
{
$html = <<<EOF
<body class="" style="" data-gr-c-s-loaded="true">123<a>456789</a><span>101112</span></body>
EOF;
$dom = new Dom();
$dom->loadStr($html);
$this->assertEquals($dom->innerText, "123456789101112");
}

public function testMultipleSquareSelector()
{
$dom = new Dom();
Expand Down
14 changes: 14 additions & 0 deletions tests/Node/HtmlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,20 @@ public function testTextLookInChildren()
$this->assertEquals('Please click me!', $node->text(true));
}

public function testInnerText()
{
$node = new HtmlNode('div');
$node->addChild(new TextNode('123 '));
$anode = new HtmlNode('a');
$anode->addChild(new TextNode('456789 '));
$span_node = new HtmlNode('span');
$span_node->addChild(new TextNode('101112'));

$node->addChild($anode);
$node->addChild($span_node);
$this->assertEquals($node->innerText(), '123 456789 101112');
}

public function testTextLookInChildrenAndNoChildren()
{
$p = new HtmlNode('p');
Expand Down

0 comments on commit a2c5eb1

Please sign in to comment.