Skip to content

Commit

Permalink
Make inputArray behave like filter_input_array and return null when n…
Browse files Browse the repository at this point in the history
…o data available
  • Loading branch information
brianlmoon committed Mar 26, 2024
1 parent 23c1b84 commit 4bf2c0a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 10 deletions.
25 changes: 24 additions & 1 deletion src/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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) {
Expand Down
30 changes: 21 additions & 9 deletions tests/FilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use DealNews\Filter\Filter;

class FilterTest extends \PHPUnit\Framework\TestCase {

/**
* Test the input methods that they don't throw errors
*/
Expand All @@ -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);
}

/**
Expand Down Expand Up @@ -114,8 +128,6 @@ public function varArrayData() {
],
],



];
}

Expand Down

0 comments on commit 4bf2c0a

Please sign in to comment.