Skip to content

Commit

Permalink
[+]: merge upstream-changes
Browse files Browse the repository at this point in the history
  • Loading branch information
voku committed Dec 28, 2018
1 parent 7c71fab commit 248c431
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/voku/helper/SimpleHtmlDom.php
Expand Up @@ -14,7 +14,7 @@
* @property string outerHtml <p>Get dom node's outer html.</p>
* @property string innerText <p>Get dom node's inner html (alias for "innerHtml").</p>
* @property string innerHtml <p>Get dom node's inner html.</p>
* @property-read string plaintext <p>Get dom node's plain text.</p>
* @property string plaintext <p>Get dom node's plain text.</p>
* @property-read string tag <p>Get dom node name.</p>
* @property-read string attr <p>Get dom node attributes.</p>
*
Expand Down Expand Up @@ -160,6 +160,8 @@ public function __set($name, $value)
case 'innertext':
case 'innerhtml':
return $this->replaceChild($value);
case 'plaintext':
return $this->replaceText($value);
default:
return $this->setAttribute($name, $value);
}
Expand Down Expand Up @@ -524,6 +526,29 @@ protected function replaceChild(string $string): self
return $this;
}

/**
* Replace this node with text
*
* @param $string
*
* @return null|$this
*/
protected function replaceText($string)
{
if (empty($string)) {
$this->node->parentNode->removeChild($this->node);

return null;
}

$newElement = $this->node->ownerDocument->createTextNode($string);
$newNode = $this->node->ownerDocument->importNode($newElement, true);
$this->node->parentNode->replaceChild($newNode, $this->node);
$this->node = $newNode;

return $this;
}

/**
* Replace this node.
*
Expand Down
17 changes: 17 additions & 0 deletions tests/SimpleHtmlDomTest.php
Expand Up @@ -51,6 +51,23 @@ public function testGetNode()
static::assertInstanceOf('DOMNode', $element->getNode());
}

public function testReplaceText()
{
$html = '<div>foo</div>';
$replace = '<h1>bar</h1>';
$document = new HtmlDomParser($html);
$node = $document->getDocument()->documentElement;
$element = new SimpleHtmlDom($node);
$element->plaintext = $replace;
static::assertSame('<h1>bar</h1>', $document->outertext);
static::assertSame($replace, $document->plaintext);
static::assertSame('<h1>bar</h1>', $element->outertext);
static::assertSame($replace, $element->plaintext);
$element->plaintext = '';
static::assertSame('', $document->outertext);
static::assertSame('', $document->plaintext);
}

public function testReplaceNode()
{
$html = '<div>foo</div>';
Expand Down

0 comments on commit 248c431

Please sign in to comment.