From 4bf2c0ac671ee55df397d7ddb20aa39c1d51e770 Mon Sep 17 00:00:00 2001 From: Brian Moon Date: Tue, 26 Mar 2024 13:15:57 -0500 Subject: [PATCH] Make inputArray behave like filter_input_array and return null when no data available --- src/Filter.php | 25 ++++++++++++++++++++++++- tests/FilterTest.php | 30 +++++++++++++++++++++--------- 2 files changed, 45 insertions(+), 10 deletions(-) diff --git a/src/Filter.php b/src/Filter.php index e0012a5..f3cce43 100644 --- a/src/Filter.php +++ b/src/Filter.php @@ -83,6 +83,30 @@ public function var(mixed $value, int $filter = FILTER_DEFAULT, array|int $optio * @see https://www.php.net/manual/en/function.filter-input-array.php */ public function inputArray(int $type, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null { + $empty = false; + switch ($type) { + case INPUT_GET: + $empty = empty($_GET); + break; + case INPUT_POST: + $empty = empty($_POST); + break; + case INPUT_COOKIE: + $empty = empty($_COOKIE); + break; + case INPUT_SERVER: + $empty = empty($_SERVER); + break; + case INPUT_ENV: + $empty = empty($_ENV); + break; + } + + // this is how filter_input_array behaves + if ($empty) { + return null; + } + return $this->varArray(filter_input_array($type) ?? [], $options, $add_empty); } @@ -158,7 +182,6 @@ public function fixOptions(array|int $options): array|int { 'options' => $this->sanitizeString(), ]; } elseif (is_array($filter) && $filter['filter'] === $this::FILTER_SANITIZE_STRING) { - if (!empty($filter['flags']) && is_array($filter['flags'])) { $flags = 0; foreach ($filter['flags'] as $flag) { diff --git a/tests/FilterTest.php b/tests/FilterTest.php index ba2599c..cfa6127 100644 --- a/tests/FilterTest.php +++ b/tests/FilterTest.php @@ -5,7 +5,6 @@ use DealNews\Filter\Filter; class FilterTest extends \PHPUnit\Framework\TestCase { - /** * Test the input methods that they don't throw errors */ @@ -20,13 +19,28 @@ public function testInput() { */ public function testInputArray() { $f = Filter::init(); + $value = $f->inputArray(INPUT_GET, ['foo' => FILTER_VALIDATE_INT]); + $this->assertNull($value); $value = $f->inputArray(INPUT_POST, ['foo' => FILTER_VALIDATE_INT]); - $this->assertSame( - [ - 'foo' => null - ], - $value - ); + $this->assertNull($value); + $value = $f->inputArray(INPUT_COOKIE, ['foo' => FILTER_VALIDATE_INT]); + $this->assertNull($value); + + $expect = array_slice($_SERVER, 0, 5); + $keys = []; + $expect_bug = []; + foreach (array_keys($expect) as $key) { + $keys[$key] = FILTER_UNSAFE_RAW; + // https://bugs.php.net/bug.php?id=49184 + // filtering on INPUT_SERVER yields an array with null values + $expect_bug[$key] = null; + } + + $value = $f->inputArray(INPUT_SERVER, $keys); + $this->assertEquals($expect_bug, $value); + + $value = $f->inputArray(INPUT_ENV, $keys); + $this->assertEquals($expect, $value); } /** @@ -114,8 +128,6 @@ public function varArrayData() { ], ], - - ]; }