From f7b172a14c3fc8a391ed5a60aaaf77b98f38f2a0 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Mon, 8 Jan 2024 13:33:39 +0100 Subject: [PATCH 1/2] feat: escape html in view params by default --- src/View.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/View.php b/src/View.php index ef2796af..a947daf6 100755 --- a/src/View.php +++ b/src/View.php @@ -77,12 +77,16 @@ public function __construct(string $path = '') * * @throws Exception */ - public function setParam(string $key, mixed $value): static + public function setParam(string $key, mixed $value, bool $escapeHtml = true): static { if (\strpos($key, '.') !== false) { throw new Exception('$key can\'t contain a dot "." character'); } + if (is_string($value) && $escapeHtml) { + $value = htmlspecialchars($value, encoding: 'UTF-8'); + } + $this->params[$key] = $value; return $this; From 5b62a82419fab611fa1c99f1243f15d3114d88d9 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Mon, 8 Jan 2024 13:39:26 +0100 Subject: [PATCH 2/2] test: add tests for escaped html --- src/View.php | 2 +- tests/ViewTest.php | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/View.php b/src/View.php index a947daf6..55e80a67 100755 --- a/src/View.php +++ b/src/View.php @@ -84,7 +84,7 @@ public function setParam(string $key, mixed $value, bool $escapeHtml = true): st } if (is_string($value) && $escapeHtml) { - $value = htmlspecialchars($value, encoding: 'UTF-8'); + $value = \htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); } $this->params[$key] = $value; diff --git a/tests/ViewTest.php b/tests/ViewTest.php index 9b18fb1e..e21131af 100755 --- a/tests/ViewTest.php +++ b/tests/ViewTest.php @@ -83,4 +83,10 @@ public function testCanFilterNewLinesToParagraphs() { $this->assertEquals('

line1

line2

', $this->view->print("line1\n\nline2", View::FILTER_NL2P)); } + + public function testCanSetParamWithEscapedHtml() + { + $this->view->setParam('key', 'value'); + $this->assertEquals('<html>value</html>', $this->view->getParam('key', 'default')); + } }