From 2d7b81c3ada809d87a955556bac2299a02ba3035 Mon Sep 17 00:00:00 2001 From: freek Date: Thu, 28 Feb 2019 22:34:19 +0100 Subject: [PATCH 1/2] add join method to collection --- src/Illuminate/Support/Collection.php | 28 +++++++++++++++++++++++++ tests/Support/SupportCollectionTest.php | 13 ++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 4a54ea0abc2f..c9245f7b4041 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -296,6 +296,34 @@ public function containsStrict($key, $value = null) return in_array($key, $this->items, true); } + /** + * Join all items from the collection using a string. The final items can use a separate glue string. + * + * @param string $glue + * @param string $finalGlue + * @return string + */ + public function join($glue, $finalGlue = '') + { + if ($finalGlue === '') { + return $this->implode($glue); + } + + if ($this->count() === 0) { + return ''; + } + + if ($this->count() === 1) { + return $this->last(); + } + + $collection = new static($this->items); + + $finalItem = $collection->pop(); + + return $collection->implode($glue).$finalGlue.$finalItem; + } + /** * Cross join with the given lists, returning all possible permutations. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index e6cf19855751..e3def02ed545 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -878,6 +878,19 @@ public function testCollapseWithNestedCollections() $this->assertEquals([1, 2, 3, 4, 5, 6], $data->collapse()->all()); } + public function testJoin() + { + $this->assertEquals('a, b, c', (new Collection(['a', 'b', 'c']))->join(', ')); + + $this->assertEquals('a, b and c', (new Collection(['a', 'b', 'c']))->join(', ', ' and ')); + + $this->assertEquals('a and b', (new Collection(['a', 'b']))->join(', ', ' and ')); + + $this->assertEquals('a', (new Collection(['a']))->join(', ', ' and ')); + + $this->assertEquals('', (new Collection([]))->join(', ', ' and ')); + } + public function testCrossJoin() { // Cross join with an array From 3fe21876d2e674ea48afef95b65850456c5a7987 Mon Sep 17 00:00:00 2001 From: freek Date: Fri, 1 Mar 2019 07:54:29 +0100 Subject: [PATCH 2/2] only count once --- src/Illuminate/Support/Collection.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index c9245f7b4041..e3a1ae2b5950 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -309,11 +309,13 @@ public function join($glue, $finalGlue = '') return $this->implode($glue); } - if ($this->count() === 0) { + $count = $this->count(); + + if ($count === 0) { return ''; } - if ($this->count() === 1) { + if ($count === 1) { return $this->last(); }