Skip to content

Commit

Permalink
Filters::safeUrl() accepts Stringable
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Sep 13, 2023
1 parent bbc6174 commit 0ae3566
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/Latte/Runtime/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,11 @@ public static function convertHtmlToText(string $s): string
/**
* Sanitizes string for use inside href attribute.
*/
public static function safeUrl(string|HtmlStringable $s): string
public static function safeUrl(string|\Stringable $s): string
{
if ($s instanceof HtmlStringable) {
$s = self::convertHtmlToText((string) $s);
}
$s = $s instanceof HtmlStringable
? self::convertHtmlToText((string) $s)
: (string) $s;

return preg_match('~^(?:(?:https?|ftp)://[^@]+(?:/.*)?|(?:mailto|tel|sms):.+|[/?#].*|[^:]+)$~Di', $s) ? $s : '';
}
Expand Down
19 changes: 19 additions & 0 deletions tests/common/Safe.url.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,22 @@ Assert::match(
'<img src="https://nette.org?a=1&amp;b=&lt;a&gt;">',
$latte->renderToString('{capture $url}https://nette.org?a=1&amp;b={="<a>"}{/capture}<img src="{$url}">'),
);

Assert::match(
'<img src="">',
$latte->renderToString('{capture $url}&#x6a;&#x61;vascript:foo{/capture}<img src="{$url}">'),
);

// accepts Stringable
Assert::match(
'<img src="&lt;a&gt;">',
$latte->renderToString(
'<img src="{$url}">',
['url' => new class {
public function __toString()
{
return '<a>';
}
}],
),
);

0 comments on commit 0ae3566

Please sign in to comment.