Skip to content

Commit

Permalink
fix: Empty Traversable in randomElements() (#605)
Browse files Browse the repository at this point in the history
* fix: Empty `Traversable` in `randomElements()`

* Fix: Remove *unmatched* `ignoreErrors` due to code changes.
  • Loading branch information
KentarouTakeda authored Apr 2, 2023
1 parent abf5e11 commit feb1640
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 7 deletions.
5 changes: 0 additions & 5 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -648,11 +648,6 @@ parameters:
count: 1
path: src/Faker/Provider/Base.php

-
message: "#^Ternary operator condition is always false\\.$#"
count: 1
path: src/Faker/Provider/Base.php

-
message: "#^Unreachable statement \\- code above always terminates\\.$#"
count: 1
Expand Down
4 changes: 2 additions & 2 deletions src/Faker/Provider/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,15 +190,15 @@ public static function randomAscii()
public static function randomElements($array = ['a', 'b', 'c'], $count = 1, $allowDuplicates = false)
{
$traversables = [];
$arr = $array;

if ($array instanceof \Traversable) {
foreach ($array as $element) {
$traversables[] = $element;
}
$arr = $traversables;
}

$arr = count($traversables) ? $traversables : $array;

$allKeys = array_keys($arr);
$numKeys = count($allKeys);

Expand Down
4 changes: 4 additions & 0 deletions test/Faker/Provider/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,10 @@ public function testRandomElements(): void
self::assertIsArray($empty);
self::assertCount(0, $empty);

$emptyTraversable = BaseProvider::randomElements(new \ArrayIterator(), 0);
self::assertIsArray($emptyTraversable);
self::assertCount(0, $emptyTraversable);

$shuffled = BaseProvider::randomElements(['foo', 'bar', 'baz'], 3);
self::assertContains('foo', $shuffled);
self::assertContains('bar', $shuffled);
Expand Down

0 comments on commit feb1640

Please # to comment.