From 314528801bba4885b75b1d4476d5be57b9975c80 Mon Sep 17 00:00:00 2001 From: Shish Date: Tue, 27 Jun 2023 15:42:42 +0100 Subject: [PATCH] make clamp() more robust --- core/polyfills.php | 8 ++------ core/tests/polyfills.test.php | 13 ++++++++----- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/core/polyfills.php b/core/polyfills.php index 437b25ed..1b6b9cfc 100644 --- a/core/polyfills.php +++ b/core/polyfills.php @@ -228,10 +228,6 @@ if (!function_exists('http_parse_headers')) { */ function find_header(array $headers, string $name): ?string { - if (!is_array($headers)) { - return null; - } - $header = null; if (array_key_exists($name, $headers)) { @@ -457,9 +453,9 @@ function page_number(string $input, ?int $max=null): int return $pageNumber; } -function clamp(?int $val, ?int $min=null, ?int $max=null): int +function clamp(int $val, ?int $min=null, ?int $max=null): int { - if (!is_numeric($val) || (!is_null($min) && $val < $min)) { + if (!is_null($min) && $val < $min) { $val = $min; } if (!is_null($max) && $val > $max) { diff --git a/core/tests/polyfills.test.php b/core/tests/polyfills.test.php index edae790a..a196da3b 100644 --- a/core/tests/polyfills.test.php +++ b/core/tests/polyfills.test.php @@ -73,11 +73,14 @@ class PolyfillsTest extends TestCase public function test_clamp() { - $this->assertEquals(5, clamp(0, 5, 10)); - $this->assertEquals(5, clamp(5, 5, 10)); - $this->assertEquals(7, clamp(7, 5, 10)); - $this->assertEquals(10, clamp(10, 5, 10)); - $this->assertEquals(10, clamp(15, 5, 10)); + $this->assertEquals(5, clamp(0, 5, 10)); // too small + $this->assertEquals(5, clamp(5, 5, 10)); // lower limit + $this->assertEquals(7, clamp(7, 5, 10)); // ok + $this->assertEquals(10, clamp(10, 5, 10)); // upper limit + $this->assertEquals(10, clamp(15, 5, 10)); // too large + $this->assertEquals(0, clamp(0, null, 10)); // no lower limit + $this->assertEquals(10, clamp(10, 0, null)); // no upper limit + $this->assertEquals(42, clamp(42, null, null)); // no limit } public function test_truncate()