Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Add operator support to Collection@partition #22380

Merged
merged 1 commit into from
Dec 10, 2017
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
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