Skip to content

Commit 448d0a9

Browse files
authored
feat(collectBy): support dot-notation (#247)
1 parent 6f4e1fd commit 448d0a9

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/Macros/CollectBy.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Spatie\CollectionMacros\Macros;
44

5+
use Illuminate\Support\Arr;
56
use Illuminate\Support\Collection;
67

78
/**
@@ -19,7 +20,7 @@ class CollectBy
1920
public function __invoke()
2021
{
2122
return function ($key, $default = null): Collection {
22-
return new static($this->get($key, $default));
23+
return new static(Arr::get($this->items, $key, $default));
2324
};
2425
}
2526
}

tests/Macros/CollectByTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,22 @@
6060

6161
expect($ingredients)->toEqual(new Collection());
6262
});
63+
64+
it('collects path from collection using dot notation', function () {
65+
$collection = new Collection([
66+
'baz.qux' => 'quux',
67+
'foo' => [
68+
'bar' => [
69+
'baz' => 100,
70+
],
71+
],
72+
]);
73+
74+
expect($collection->collectBy('foo.bar'))->toBeInstanceOf(Collection::class);
75+
expect($collection->collectBy('foo.bar')->toArray())->toEqual([
76+
'baz' => 100,
77+
]);
78+
79+
expect($collection->collectBy('baz.qux'))->toBeInstanceOf(Collection::class);
80+
expect($collection->collectBy('baz.qux')->toArray())->toEqual(['quux']);
81+
});

0 commit comments

Comments
 (0)