Skip to content

Commit

Permalink
[BUGFIX] Correctly import nodes with different owner document
Browse files Browse the repository at this point in the history
  • Loading branch information
ohader committed Oct 20, 2023
1 parent c1a88e7 commit bd5c573
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/Sanitizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,11 @@ protected function replaceNode(DOMNode $source, $target)
if ($target === null) {
$source->parentNode->removeChild($source);
} elseif ($source !== $target) {
if ($source->ownerDocument !== $target->ownerDocument) {
$source->ownerDocument->importNode($target);
if ($source->ownerDocument !== $target->ownerDocument
&& $source->ownerDocument !== null
&& $target->ownerDocument !== null
) {
$target = $source->ownerDocument->importNode($target, true);
}
$source->parentNode->replaceChild($target, $source);
}
Expand Down
36 changes: 36 additions & 0 deletions tests/ScenarioTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,42 @@ public function tagIsHandled(Behavior\NodeHandler $nodeHandler, string $payload,
self::assertSame($expectation, $sanitizer->sanitize($payload));
}

/**
* @test
*/
public function tagHandlingIsDelegated(): void
{
$behavior = (new Behavior())
->withFlags(Behavior::REMOVE_UNEXPECTED_CHILDREN)
->withName('scenario-test')
->withTags(new Behavior\Tag('div', Behavior\Tag::ALLOW_CHILDREN))
->withNodes(
new Behavior\NodeHandler(
new Behavior\Tag('my-placeholder'),
new Behavior\Handler\ClosureHandler(
static function (NodeInterface $node, ?DOMNode $domNode): ?\DOMNode {
if ($domNode === null) {
return null;
}
$newDocument = new \DOMDocument();
$text = $newDocument->createTextNode($domNode->textContent);
$span = $newDocument->createElement('div');
$span->setAttribute('class', 'delegated');
$span->appendChild($text);
return $span;
}
)
)
);
$sanitizer = new Sanitizer(
$behavior,
new CommonVisitor($behavior)
);
$payload = '<div><my-placeholder><span class="inner">value</span></my-placeholder></div>';
$expectation = '<div><div class="delegated">value</div></div>';
self::assertSame($expectation, $sanitizer->sanitize($payload));
}

public static function commentsAreHandledDataProvider(): array
{
return [
Expand Down

0 comments on commit bd5c573

Please sign in to comment.