Skip to content

Commit

Permalink
Fixed silent failure when constructor not called
Browse files Browse the repository at this point in the history
- Closed #55
  • Loading branch information
PerryRylance committed Feb 26, 2022
1 parent 5a55e5d commit 616d465
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/DOMDocument.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
class DOMDocument extends \DOMDocument
{
private $constructorCalled = false; // NB: Used to signal bad state, otherwise we get silent failure when trying to loadHTML before calling constructor

const UNDEFINED = "b0814351-6e51-4134-a77b-8e5fbec4e026"; // NB: Used to differentiate between explicit null and argument not supplied, for example in DOMQueryResults::css

/**
Expand All @@ -23,7 +25,8 @@ class DOMDocument extends \DOMDocument
public function __construct($version='1.0', $encoding='UTF-8')
{
\DOMDocument::__construct($version, $encoding);


$this->constructorCalled = true;
$this->registerNodeClass('DOMElement', 'PerryRylance\DOMDocument\DOMElement');
}

Expand Down Expand Up @@ -114,6 +117,9 @@ public function shorthand()
*/
public function loadHTML($src, $options=array())
{
if(!$this->constructorCalled)
throw new \Exception("Bad state (did you try to loadHTML before calling constructor?)");

if(empty($options))
$options = [];

Expand Down
15 changes: 15 additions & 0 deletions tests/DOMDocumentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
use PerryRylance\DOMDocument;
use PHPUnit\Framework\TestCase;

class DOMDocumentBadInit extends DOMDocument
{
public function __construct()
{
$this->loadHTML("This should throw a bad state exception, because the parent class is not initialized");
}
}

final class DOMDocumentTest extends TestCase
{
private function getDocument()
Expand Down Expand Up @@ -385,4 +393,11 @@ public function testShorthandMethod()

$this->assertTrue( !$failed );
}

public function testCloneNode()
{
$this->expectException(Exception::class);

$document = new DOMDocumentBadInit();
}
}

0 comments on commit 616d465

Please sign in to comment.