From 884ee096c8c5501f3ea87e97314b4373991b04a7 Mon Sep 17 00:00:00 2001 From: Benson Lee Date: Thu, 27 Apr 2017 08:27:15 -0700 Subject: [PATCH] Laravel 5.4.20 changes (#41) --- src/Illuminate/Support/Collection.php | 19 ++++++++++++++++ tests/Support/SupportCollectionTest.php | 29 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index f978c52..4a879bd 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -704,6 +704,25 @@ public function map(callable $callback) return new static(array_combine($keys, $items)); } + /** + * Run a grouping map over the items. + * + * The callback should return an associative array with a single key/value pair. + * + * @param callable $callback + * @return static + */ + public function mapToGroups(callable $callback) + { + $groups = $this->map($callback)->reduce(function ($groups, $pair) { + $groups[key($pair)][] = reset($pair); + + return $groups; + }, []); + + return (new static($groups))->map([$this, 'make']); + } + /** * Run an associative map over each of the items. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index a806848..a05adfa 100644 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -1049,6 +1049,35 @@ public function testFlatMap() $this->assertEquals(['programming', 'basketball', 'music', 'powerlifting'], $data->all()); } + public function testMapToGroups() + { + $data = new Collection([ + ['id' => 1, 'name' => 'A'], + ['id' => 2, 'name' => 'B'], + ['id' => 3, 'name' => 'C'], + ['id' => 4, 'name' => 'B'], + ]); + + $groups = $data->mapToGroups(function ($item, $key) { + return [$item['name'] => $item['id']]; + }); + + $this->assertInstanceOf(Collection::class, $groups); + $this->assertEquals(['A' => [1], 'B' => [2, 4], 'C' => [3]], $groups->toArray()); + $this->assertInstanceOf(Collection::class, $groups['A']); + } + + public function testMapToGroupsWithNumericKeys() + { + $data = new Collection([1, 2, 3, 2, 1]); + + $groups = $data->mapToGroups(function ($item, $key) { + return [$item => $key]; + }); + + $this->assertEquals([1 => [0, 4], 2 => [1, 3], 3 => [2]], $groups->toArray()); + } + public function testMapWithKeys() { $data = new Collection([