Skip to content

Commit

Permalink
Merge pull request #8 from gam6itko/array_is_list
Browse files Browse the repository at this point in the history
ArrayChecker add methods [isList, isAssoc]
  • Loading branch information
butschster committed Dec 13, 2022
2 parents 3556ad0 + 095886c commit 4be2bd2
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Checker/ArrayChecker.php
Expand Up @@ -15,6 +15,8 @@ class ArrayChecker extends AbstractChecker
'longer' => '[[Number of elements must be equal to or greater than {1}.]]',
'shorter' => '[[Number of elements must be equal to or less than {1}.]]',
'range' => '[[Number of elements must be between {1} and {2}.]]',
'isList' => '[[Array is not list]]',
'isAssoc' => '[[Array is not associative]]',
];

public function __construct(
Expand Down Expand Up @@ -74,4 +76,14 @@ public function range(mixed $value, int $min, int $max): bool

return $count >= $min && $count <= $max;
}

public function isList(mixed $value): bool
{
return is_array($value) && array_is_list($value);
}

public function isAssoc(mixed $value): bool
{
return is_array($value) && !array_is_list($value);
}
}
80 changes: 80 additions & 0 deletions tests/src/Unit/Checkers/ArrayTest.php
Expand Up @@ -89,4 +89,84 @@ public function count(): int
}
};
}

/**
* @dataProvider dataIsList
*/
public function testIsList(mixed $value, bool $expectedResult): void
{
/** @var ArrayChecker $checker */
$checker = $this->container->get(ArrayChecker::class);
self::assertSame($expectedResult, $checker->isList($value));
}

public function dataIsList(): iterable
{
yield [[], true];
yield [[1, 2, 3], true];
yield [['a', 'b', 'c'], true];
yield [
[0 => 'a', 1 => 'b', 2 => 'c'],
true,
];
yield [
['0' => 'a', '1' => 'b', '2' => 'c'],
true,
];
yield [
['name' => 'name', 1, 2, 3],
false,
];
yield [
['name' => 'foo', 'surname' => 'bar'],
false,
];

yield ['', false];
yield [1, false];
yield [2.0, false];
yield ['foo', false];
yield [null, false];
yield [new \stdClass(), false];
}

/**
* @dataProvider dataIsAssoc
*/
public function testIsAssoc(mixed $value, bool $expectedResult): void
{
/** @var ArrayChecker $checker */
$checker = $this->container->get(ArrayChecker::class);
self::assertSame($expectedResult, $checker->isAssoc($value));
}

public function dataIsAssoc(): iterable
{
yield [[], false];
yield [[1, 2, 3], false];
yield [['a', 'b', 'c'], false];
yield [
[0 => 'a', 1 => 'b', 2 => 'c'],
false,
];
yield [
['0' => 'a', '1' => 'b', '2' => 'c'],
false,
];
yield [
['name' => 'name', 1, 2, 3],
true,
];
yield [
['name' => 'foo', 'surname' => 'bar'],
true,
];

yield ['', false];
yield [1, false];
yield [2.0, false];
yield ['foo', false];
yield [null, false];
yield [new \stdClass(), false];
}
}

0 comments on commit 4be2bd2

Please sign in to comment.