Skip to content

Commit

Permalink
Add operator support to Collection@partition (#22380)
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber authored and taylorotwell committed Dec 10, 2017
1 parent 46bf9c2 commit 0917899
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1070,14 +1070,18 @@ public function forPage($page, $perPage)
/**
* Partition the collection into two arrays using the given callback or key.
*
* @param callable|string $callback
* @param callable|string $key
* @param mixed $operator
* @param mixed $value
* @return static
*/
public function partition($callback)
public function partition($key, $operator = null, $value = null)
{
$partitions = [new static, new static];

$callback = $this->valueRetriever($callback);
$callback = func_num_args() == 1
? $this->valueRetriever($key)
: $this->operatorForWhere(...func_get_args());

foreach ($this->items as $key => $item) {
$partitions[(int) ! $callback($item, $key)][$key] = $item;
Expand Down
34 changes: 34 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2309,6 +2309,40 @@ public function testPartitionByKey()
$this->assertSame([['free' => false, 'title' => 'Premium']], $premium->values()->toArray());
}

public function testPartitionWithOperators()
{
$collection = new Collection([
['name' => 'Tim', 'age' => 17],
['name' => 'Agatha', 'age' => 62],
['name' => 'Kristina', 'age' => 33],
['name' => 'Tim', 'age' => 41],
]);

list($tims, $others) = $collection->partition('name', 'Tim');

$this->assertEquals($tims->values()->all(), [
['name' => 'Tim', 'age' => 17],
['name' => 'Tim', 'age' => 41],
]);

$this->assertEquals($others->values()->all(), [
['name' => 'Agatha', 'age' => 62],
['name' => 'Kristina', 'age' => 33],
]);

list($adults, $minors) = $collection->partition('age', '>=', 18);

$this->assertEquals($adults->values()->all(), [
['name' => 'Agatha', 'age' => 62],
['name' => 'Kristina', 'age' => 33],
['name' => 'Tim', 'age' => 41],
]);

$this->assertEquals($minors->values()->all(), [
['name' => 'Tim', 'age' => 17],
]);
}

public function testPartitionPreservesKeys()
{
$courses = new Collection([
Expand Down

0 comments on commit 0917899

Please sign in to comment.