From 0917899a5d75521fc013462e3bca66396fc65c73 Mon Sep 17 00:00:00 2001 From: Joseph Silber Date: Sun, 10 Dec 2017 14:19:34 +0000 Subject: [PATCH] Add operator support to Collection@partition (#22380) --- src/Illuminate/Support/Collection.php | 10 +++++--- tests/Support/SupportCollectionTest.php | 34 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 1cf0447d3c0f..d6184f31bae4 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -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; diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 678f285c3aca..dc226e01fd41 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -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([