From feb1640cb67f08c3a2f98fb27fd6875be60fd2ad Mon Sep 17 00:00:00 2001 From: KentarouTakeda Date: Sun, 2 Apr 2023 16:55:47 +0900 Subject: [PATCH] fix: Empty `Traversable` in `randomElements()` (#605) * fix: Empty `Traversable` in `randomElements()` * Fix: Remove *unmatched* `ignoreErrors` due to code changes. --- phpstan-baseline.neon | 5 ----- src/Faker/Provider/Base.php | 4 ++-- test/Faker/Provider/BaseTest.php | 4 ++++ 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 8d1e9c6c9d..4c24bc5a7e 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -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 diff --git a/src/Faker/Provider/Base.php b/src/Faker/Provider/Base.php index e3713ce0e6..f4fb6398e6 100644 --- a/src/Faker/Provider/Base.php +++ b/src/Faker/Provider/Base.php @@ -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); diff --git a/test/Faker/Provider/BaseTest.php b/test/Faker/Provider/BaseTest.php index 0cf06b768d..65ae520c3b 100644 --- a/test/Faker/Provider/BaseTest.php +++ b/test/Faker/Provider/BaseTest.php @@ -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);