Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.8] Add join method to collection #27723

Merged
merged 2 commits into from
Mar 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,36 @@ 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 = '')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe rename finalGlue to lastGlue?

{
if ($finalGlue === '') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we change the default value to null instead of '', as this removes the option for having an empty string as your finalGlue.

return $this->implode($glue);
}

$count = $this->count();

if ($count === 0) {
return '';
}

if ($count === 1) {
return $this->last();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be cast to string explicitly?

}

$collection = new static($this->items);

$finalItem = $collection->pop();

return $collection->implode($glue).$finalGlue.$finalItem;
}

/**
* Cross join with the given lists, returning all possible permutations.
*
Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down