Skip to content

Commit

Permalink
Fix: allow empty maps and lists (webmozarts#152)
Browse files Browse the repository at this point in the history
* Expecting `isList` to allow empty arrays and lists composed of non-list items

* Corrected `Assert::isList()` to accept empty lists as valid lists

* Expecting empty maps to be valid according to `Assert::isMap()`

* Corrected `Assert::isMap()` to accept empty maps

* Simplified `Assert::isMap()` internal mapping over keys
  • Loading branch information
Ocramius authored and BackEndTea committed Nov 23, 2019
1 parent 6176403 commit 7e202b1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
7 changes: 2 additions & 5 deletions src/Assert.php
Original file line number Diff line number Diff line change
Expand Up @@ -1699,7 +1699,7 @@ public static function countBetween($array, $min, $max, $message = '')
*/
public static function isList($array, $message = '')
{
if (!\is_array($array) || !$array || \array_keys($array) !== \range(0, \count($array) - 1)) {
if (!\is_array($array) || $array !== \array_values($array)) {
static::reportInvalidArgument(
$message ?: 'Expected list - non-associative array.'
);
Expand All @@ -1716,10 +1716,7 @@ public static function isMap($array, $message = '')
{
if (
!\is_array($array) ||
!$array ||
\array_keys($array) !== \array_filter(\array_keys($array), function ($key) {
return \is_string($key);
})
\array_keys($array) !== \array_filter(\array_keys($array), 'is_string')
) {
static::reportInvalidArgument(
$message ?: 'Expected map - associative array with string keys.'
Expand Down
8 changes: 6 additions & 2 deletions tests/AssertTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -425,13 +425,17 @@ public function getTests()
array('countBetween', array(array(0, 1, 2), 2, 5), true),
array('countBetween', array(array(0, 1, 2), 2, 3), true),
array('isList', array(array(1, 2, 3)), true),
array('isList', array(array()), false),
array('isList', array(array()), true),
array('isList', array(array(0 => 1, 2 => 3)), false),
array('isList', array(array('key' => 1, 'foo' => 2)), false),
array('isList', array(true), false),
array('isList', array(false), false),
array('isList', array(array(true)), true),
array('isList', array(array(false)), true),
array('isList', array(array(array(1), array(2))), true),
array('isList', array(array(array('foo' => 'bar'), array('baz' => 'tab'))), true),
array('isMap', array(array('key' => 1, 'foo' => 2)), true),
array('isMap', array(array()), false),
array('isMap', array(array()), true),
array('isMap', array(array(1, 2, 3)), false),
array('isMap', array(array(0 => 1, 2 => 3)), false),
array('uuid', array('00000000-0000-0000-0000-000000000000'), true),
Expand Down

0 comments on commit 7e202b1

Please sign in to comment.