File tree Expand file tree Collapse file tree 2 files changed +14
-3
lines changed
src/Illuminate/Collections Expand file tree Collapse file tree 2 files changed +14
-3
lines changed Original file line number Diff line number Diff line change @@ -979,21 +979,22 @@ public function put($key, $value)
979
979
* Get one or a specified number of items randomly from the collection.
980
980
*
981
981
* @param (callable(TValue): int)|int|null $number
982
+ * @param bool $preserveKeys
982
983
* @return static<int, TValue>|TValue
983
984
*
984
985
* @throws \InvalidArgumentException
985
986
*/
986
- public function random ($ number = null )
987
+ public function random ($ number = null , $ preserveKeys = false )
987
988
{
988
989
if (is_null ($ number )) {
989
990
return Arr::random ($ this ->items );
990
991
}
991
992
992
993
if (is_callable ($ number )) {
993
- return new static (Arr::random ($ this ->items , $ number ($ this )));
994
+ return new static (Arr::random ($ this ->items , $ number ($ this ), $ preserveKeys ));
994
995
}
995
996
996
- return new static (Arr::random ($ this ->items , $ number ));
997
+ return new static (Arr::random ($ this ->items , $ number, $ preserveKeys ));
997
998
}
998
999
999
1000
/**
Original file line number Diff line number Diff line change @@ -2286,9 +2286,19 @@ public function testRandom($collection)
2286
2286
$ this ->assertInstanceOf ($ collection , $ random );
2287
2287
$ this ->assertCount (2 , $ random );
2288
2288
2289
+ $ random = $ data ->random (2 , true );
2290
+ $ this ->assertInstanceOf ($ collection , $ random );
2291
+ $ this ->assertCount (2 , $ random );
2292
+ $ this ->assertCount (2 , array_intersect_assoc ($ random ->all (), $ data ->all ()));
2293
+
2289
2294
$ random = $ data ->random (fn ($ items ) => min (10 , count ($ items )));
2290
2295
$ this ->assertInstanceOf ($ collection , $ random );
2291
2296
$ this ->assertCount (6 , $ random );
2297
+
2298
+ $ random = $ data ->random (fn ($ items ) => min (10 , count ($ items ) - 1 ), true );
2299
+ $ this ->assertInstanceOf ($ collection , $ random );
2300
+ $ this ->assertCount (5 , $ random );
2301
+ $ this ->assertCount (5 , array_intersect_assoc ($ random ->all (), $ data ->all ()));
2292
2302
}
2293
2303
2294
2304
/**
You can’t perform that action at this time.
0 commit comments