From afdcf3b675da5478ff6322a67f74ec729ea3d43b Mon Sep 17 00:00:00 2001 From: didac-adria Date: Tue, 18 Apr 2023 10:45:02 +0200 Subject: [PATCH] Add merge method to Data Collections --- src/Concerns/EnumerableMethods.php | 15 +++++++++++++++ tests/DataCollectionTest.php | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/Concerns/EnumerableMethods.php b/src/Concerns/EnumerableMethods.php index 163253da..0cf94c8c 100644 --- a/src/Concerns/EnumerableMethods.php +++ b/src/Concerns/EnumerableMethods.php @@ -3,6 +3,7 @@ namespace Spatie\LaravelData\Concerns; use Spatie\LaravelData\Contracts\DataCollectable; +use Spatie\LaravelData\DataCollection; /** * @template TKey of array-key @@ -125,4 +126,18 @@ public function sole(callable|string|null $key = null, mixed $operator = null, m { return $this->items->sole(...func_get_args()); } + + /** + * @param DataCollection $collection + * + * @return static + */ + public function merge(DataCollection $collection): static + { + $cloned = clone $this; + + $cloned->items = $cloned->items->merge($collection->items); + + return $cloned; + } } diff --git a/tests/DataCollectionTest.php b/tests/DataCollectionTest.php index 06a4d18c..3c3a91b8 100644 --- a/tests/DataCollectionTest.php +++ b/tests/DataCollectionTest.php @@ -480,6 +480,20 @@ function (string $operation, array $arguments, array $expected) { ->toEqual($filtered->string); }); +test('a collection can be merged', function () { + $collectionA = SimpleData::collection(['A', 'B']); + $collectionB = SimpleData::collection(['C', 'D']); + + $filtered = $collectionA->merge($collectionB)->toArray(); + + expect([ + ['string' => 'A'], + ['string' => 'B'], + ['string' => 'C'], + ['string' => 'D'], + ]) + ->toMatchArray($filtered); +}); it('can serialize and unserialize a data collection', function () { $collection = SimpleData::collection(['A', 'B']);