Skip to content

Commit

Permalink
feat(collectBy): support dot-notation
Browse files Browse the repository at this point in the history
  • Loading branch information
innocenzi committed Oct 16, 2023
1 parent 6f4e1fd commit 41e7126
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Macros/CollectBy.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\CollectionMacros\Macros;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;

/**
Expand All @@ -19,7 +20,7 @@ class CollectBy
public function __invoke()
{
return function ($key, $default = null): Collection {
return new static($this->get($key, $default));
return new static(Arr::get($this->items, $key, $default));
};
}
}
19 changes: 19 additions & 0 deletions tests/Macros/CollectByTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,22 @@

expect($ingredients)->toEqual(new Collection());
});

it('collects path from collection using dot notation', function () {
$collection = new Collection([
'baz.qux' => 'quux',
'foo' => [
'bar' => [
'baz' => 100,
],
],
]);

expect($collection->collectBy('foo.bar'))->toBeInstanceOf(Collection::class);
expect($collection->collectBy('foo.bar')->toArray())->toEqual([
'baz' => 100,
]);

expect($collection->collectBy('baz.qux'))->toBeInstanceOf(Collection::class);
expect($collection->collectBy('baz.qux')->toArray())->toEqual(['quux']);
});

0 comments on commit 41e7126

Please sign in to comment.