Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ $ composer cs
## Fix Code Standard Failures
To automatically fix code standard failures, run this command:
```sh
$ composer fix-cs
$ composer cs-fix
```

## Manual
Expand Down Expand Up @@ -455,3 +455,10 @@ return a new instance of the collection with the shuffled data:
$collection = new Collection([1,2,3,4,5]);
$shuffled = $collection->shuffle();
```
`shuffle()` also takes an optional integer _seed_, which will be used to
determine the start state of the pseudo random number generator (`mt_rand()`)
that is used to determine the order that elements are shuffled into.

If you use the _seed_ with `shuffle()`, the resulting collection will always
have its elements in the same order for a given original collection and seed
value. It will never return a different order for this combination.
6 changes: 5 additions & 1 deletion src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,14 @@ public function asort(callable $callable = null): self
/**
* Get a New Collection With Contents Shuffled
*
* @param $seed int|null
* @return static
*/
public function shuffle(): self
public function shuffle(int $seed = null): self
{
if ($seed !== null) {
mt_srand($seed);
}
$data = $this->getArrayCopy();
shuffle($data);
return $this->getNewInstance($data);
Expand Down
24 changes: 24 additions & 0 deletions tests/CollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,22 @@ public function shuffle($data)
$this->assertNotEquals($shuffledArray, $data);
}

/**
* @dataProvider shuffles
* @param $data array
* @param $seed string|int
* @param $expected array
* @test
*/
public function shuffleWithSeed($data, $seed, $expected)
{
$collection = new Collection($data);
$shuffled = $collection->shuffle($seed);
$shuffledArray = $shuffled->getArrayCopy();
$this->assertNotEquals($shuffledArray, $data);
$this->assertEquals($shuffledArray, $expected);
}

/**
* @test
*/
Expand Down Expand Up @@ -770,6 +786,14 @@ public function mismatchedTypedCollections(): array
];
}

public function shuffles(): array
{
return [
[[1,2,3,4,5,6,7,8,9,10], 15, [9,10,2,1,7,6,8,5,4,3]],
[[1,2,3,4,5,6,7,8,9,10], PHP_INT_MAX, [7,10,8,3,6,1,9,5,4,2]],
];
}

public function sorts(): array
{
return [
Expand Down