diff --git a/README.md b/README.md index 7e16f68..dfd71c5 100644 --- a/README.md +++ b/README.md @@ -464,8 +464,18 @@ have its elements in the same order for a given original collection and seed value. It will never return a different order for this combination. ### Implode -The `implode()` method will take your collection and return a string with the items joined together with `$glue` +The `implode()` method will take your collection and return a string with the +items joined together with `$glue` ```php $collection = new Collection(['a', 'b']); $joined = $collection->implode(', '); // 'a, b' ``` + +You may also pass an optional callable as the second argument which allows you +to pick the specific properties from your collected objects when imploding: +```php +$collection = new Collection($users); +$joined = $collection->implode(', ', function (User $user): string { + return $user->name(); +}); +``` diff --git a/src/Collection.php b/src/Collection.php index baa8efb..6f9d169 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -421,11 +421,13 @@ public function shuffle(int $seed = null): self * Join collection elements together with a string * * @param string $glue + * @param callable $callable * @return static */ - public function implode($glue = ""): string + public function implode($glue = "", callable $callable = null): string { - return implode($glue, $this->getArrayCopy()); + $data = $callable ? $this->map($callable)->getArrayCopy() : $this->getArrayCopy(); + return implode($glue, $data); } /** diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index 446e504..02e0ce2 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -726,6 +726,33 @@ public function itImplodesStrings(): void $this->assertSame('a, b', $collection->implode(', ')); } + /** @test */ + public function itImplodesObjects(): void + { + $newClass = function(string $foo) { + return new class($foo) { + private $foo; + public function __construct(string $foo) { + $this->foo = $foo; + } + public function foo(): string { + return $this->foo; + } + }; + }; + $collection = new Collection([ + $newClass('foo'), + $newClass('bar'), + $newClass('baz') + ]); + $this->assertSame( + 'foo, bar, baz', + $collection->implode(', ', function ($item) { + return $item->foo(); + }) + ); + } +