From decb04c983a8b0dfcb60095ad161a1bf4e87ed92 Mon Sep 17 00:00:00 2001 From: freek Date: Mon, 25 Feb 2019 19:54:24 +0100 Subject: [PATCH] add join method --- CHANGELOG.md | 2 ++ README.md | 17 +++++++++++++++++ src/macros/join.php | 27 +++++++++++++++++++++++++++ tests/Macros/JoinTest.php | 23 +++++++++++++++++++++++ 4 files changed, 69 insertions(+) create mode 100644 src/macros/join.php create mode 100644 tests/Macros/JoinTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index a558b93..a9ccf00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ All notable changes to `laravel-collection-macros` will be documented in this file +## 4.3.0 - 2019-02-25 +- add `join` macro ## 4.2.0 - 2018-12-16 - add `head` macro diff --git a/README.md b/README.md index 13eebdb..e5a6c59 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ The package will automatically register itself. - [`head`](#head) - [`ifAny`](#ifany) - [`ifEmpty`](#ifempty) +- [`join`](#join) - [`none`](#none) - [`paginate`](#paginate) - [`parallelMap`](#parallelmap) @@ -373,6 +374,22 @@ collect([1, 2, 3])->ifEmpty(function(Collection $collection) { // non-empty coll }); ``` +### `join` + +Join all items from the collection using a string. The final item can be glued with another string. + +```php +collect(['a', 'b', 'c']))->join(', ')); // returns 'a, b, c' + +collect(['a', 'b', 'c']))->join(', ', ' and ')); // returns 'a, b and c' + +collect(['a', 'b']))->join(', ', ' and ')); // returns 'a and b' + +collect(['a']))->join(', ', ' and ')); // returns 'a' + +collect([]))->join(', ', ' and ')); // returns '' +``` + ### `none` Checks whether a collection doesn't contain any occurrences of a given item, key-value pair, or passing truth test. The function accepts the same parameters as the `contains` collection method. diff --git a/src/macros/join.php b/src/macros/join.php new file mode 100644 index 0000000..76b0493 --- /dev/null +++ b/src/macros/join.php @@ -0,0 +1,27 @@ +implode($glue); + }; + + if ($this->count() === 0) { + return ''; + } + + if ($this->count() === 1) { + return $this->last(); + } + + $collection = new Collection($this->items); + + $finalItem = $collection->pop(); + + return $collection->implode($glue) . $finalGlue . $finalItem; +}); diff --git a/tests/Macros/JoinTest.php b/tests/Macros/JoinTest.php new file mode 100644 index 0000000..5c7a870 --- /dev/null +++ b/tests/Macros/JoinTest.php @@ -0,0 +1,23 @@ +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 ')); + } +}