Skip to content
This repository was archived by the owner on Jan 30, 2020. It is now read-only.

Ensures that null data passed to an input filter is cast to an empty array #161

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Ensures that null data passed to an input filter is cast to an empt…
…y array

Per #159, `BaseInputFilter` works inconsistently when a `null` value is
passed to `setData()`, interpreting this as an invalid argument type
versus an empty data set. This is particularly problematic with nested
sets sent via an API, as they may be nullable. In such cases, they
should be treated the same as if an empty array were provided.
  • Loading branch information
weierophinney committed Jan 22, 2018
commit d94f78dd385c2d9bfe7d12aa2c42f5dec12b93bd
8 changes: 7 additions & 1 deletion src/BaseInputFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,21 @@ public function remove($name)
/**
* Set data to use when validating and filtering
*
* @param array|Traversable $data
* @param null|array|Traversable $data null is cast to an empty array.
* @throws Exception\InvalidArgumentException
* @return InputFilterInterface
*/
public function setData($data)
{
// A null value indicates an empty set
if (null === $data) {
$data = [];
}

if ($data instanceof Traversable) {
$data = ArrayUtils::iteratorToArray($data);
}

if (! is_array($data)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects an array or Traversable argument; received %s',
Expand Down
26 changes: 26 additions & 0 deletions test/InputFilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,30 @@ protected function createFactoryMock()

return $factory;
}

/**
* Particularly in APIs, a null value may be passed for a set of data
* rather than an object or array. This ensures that doing so will
* work consistently with passing an empty array.
*
* @see https://github.com/zendframework/zend-inputfilter/issues/159
*/
public function testNestedInputFilterShouldAllowNullValueForData()
{
$filter1 = new InputFilter();
$filter1->add([
'type' => InputFilter::class,
'nestedField1' => [
'required' => false
]
], 'nested');

// Empty set of data
$filter1->setData([]);
self::assertNull($filter1->getValues()['nested']['nestedField1']);

// null provided for nested filter
$filter1->setData(['nested' => null]);
self::assertNull($filter1->getValues()['nested']['nestedField1']);
}
}