Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,17 @@ public function testForceAttribute()
{
$config = (new HtmlSanitizerConfig())
->allowElement('div')
->allowElement('img', '*')
->allowElement('a', ['href'])
->forceAttribute('a', 'rel', 'noopener noreferrer')
->forceAttribute('img', 'loading', 'lazy')
;

$this->assertSame(
'<img title="My image" src="https://example.com/image.png" loading="lazy" />',
$this->sanitize($config, '<img title="My image" src="https://example.com/image.png" loading="eager" onerror="alert(\'1234\')" />')
);

$this->assertSame(
'<a rel="noopener noreferrer">Hello</a> world',
$this->sanitize($config, '<a>Hello</a> world')
Expand All @@ -250,6 +257,11 @@ public function testForceAttribute()
'<div>Hello</div> world',
$this->sanitize($config, '<div style="width: 100px">Hello</div> world')
);

$this->assertSame(
'<a href="https://symfony.com" rel="noopener noreferrer">Hello</a> world',
$this->sanitize($config, '<a href="https://symfony.com" rel="noopener">Hello</a> world')
);
}

public function testForceHttps()
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/HtmlSanitizer/Visitor/DomVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ private function enterNode(string $domNodeName, \DOMNode $domNode, Cursor $curso

// Force configured attributes
foreach ($this->forcedAttributes[$domNodeName] ?? [] as $attribute => $value) {
$node->setAttribute($attribute, $value);
$node->setAttribute($attribute, $value, true);
}

$cursor->node->addChild($node);
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/HtmlSanitizer/Visitor/Node/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,10 @@ public function getAttribute(string $name): ?string
return $this->attributes[$name] ?? null;
}

public function setAttribute(string $name, ?string $value): void
public function setAttribute(string $name, ?string $value, bool $override = false): void
{
// Always use only the first declaration (ease sanitization)
if (!\array_key_exists($name, $this->attributes)) {
if ($override || !\array_key_exists($name, $this->attributes)) {
$this->attributes[$name] = $value;
}
}
Expand Down