Skip to content

Commit

Permalink
[TASK] Add AbstractHtmlProcessor::getHtmlElement() (#1335)
Browse files Browse the repository at this point in the history
This is `protected` so that it can be used by subclasses, e.g. for iterating the
DOM tree (which is likely for #1276).
  • Loading branch information
JakeQZ authored Sep 23, 2024
1 parent 294737c commit 642d2c7
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
23 changes: 18 additions & 5 deletions src/HtmlProcessor/AbstractHtmlProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,23 @@ private function removeSelfClosingTagsClosingTags(string $html): string
return (new Preg())->replace('%</' . self::PHP_UNRECOGNIZED_VOID_TAGNAME_MATCHER . '>%', '', $html);
}

/**
* Returns the HTML element.
*
* This method assumes that there always is an HTML element, throwing an exception otherwise.
*
* @throws \UnexpectedValueException
*/
protected function getHtmlElement(): \DOMElement
{
$htmlElement = $this->getDomDocument()->getElementsByTagName('html')->item(0);
if (!$htmlElement instanceof \DOMElement) {
throw new \UnexpectedValueException('There is no HTML element although there should be one.', 1569930853);
}

return $htmlElement;
}

/**
* Returns the BODY element.
*
Expand Down Expand Up @@ -456,10 +473,6 @@ private function ensureExistenceOfBodyElement(): void
return;
}

$htmlElement = $this->getDomDocument()->getElementsByTagName('html')->item(0);
if (!$htmlElement instanceof \DOMElement) {
throw new \UnexpectedValueException('There is no HTML element although there should be one.', 1569930853);
}
$htmlElement->appendChild($this->getDomDocument()->createElement('body'));
$this->getHtmlElement()->appendChild($this->getDomDocument()->createElement('body'));
}
}
12 changes: 12 additions & 0 deletions tests/Unit/HtmlProcessor/AbstractHtmlProcessorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ public function fromDomDocumentReturnsInstanceOfCalledClass(): void
self::assertInstanceOf(TestingHtmlProcessor::class, $subject);
}

/**
* @test
*/
public function getHtmlElementReturnsHtmlElement(): void
{
$subject = TestingHtmlProcessor::fromHtml('<html><head></head><body><p></p></body></html>');

$result = $subject->callGetHtmlElement();

self::assertSame('html', $result->tagName);
}

/**
* @test
*/
Expand Down
8 changes: 7 additions & 1 deletion tests/Unit/HtmlProcessor/Fixtures/TestingHtmlProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,10 @@
/**
* Fixture class for AbstractHtmlProcessor.
*/
final class TestingHtmlProcessor extends AbstractHtmlProcessor {}
final class TestingHtmlProcessor extends AbstractHtmlProcessor
{
public function callGetHtmlElement(): \DOMElement
{
return $this->getHtmlElement();
}
}

0 comments on commit 642d2c7

Please sign in to comment.