Skip to content

Commit e01de9b

Browse files
authored
Add StringUtil::joinNonEmpty()
1 parent 075f157 commit e01de9b

File tree

4 files changed

+44
-3
lines changed

4 files changed

+44
-3
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ See [GitHub releases](https://github.com/mll-lab/php-utils/releases).
99

1010
## Unreleased
1111

12+
## v1.9.0
13+
14+
### Added
15+
16+
- Add `StringUtil::joinNonEmpty()`
17+
1218
## v1.8.1
1319

1420
### Changed

composer.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,10 @@
5252
},
5353
"config": {
5454
"allow-plugins": {
55-
"ocramius/package-versions": true,
56-
"phpstan/extension-installer": true,
5755
"ergebnis/composer-normalize": true,
58-
"infection/extension-installer": true
56+
"infection/extension-installer": true,
57+
"ocramius/package-versions": true,
58+
"phpstan/extension-installer": true
5959
},
6060
"sort-packages": true
6161
},

src/StringUtil.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,19 @@
66

77
final class StringUtil
88
{
9+
/** @param iterable<string|null> $parts */
10+
public static function joinNonEmpty(string $glue, iterable $parts): string
11+
{
12+
$nonEmptyParts = [];
13+
foreach ($parts as $part) {
14+
if ($part !== '' && $part !== null) {
15+
$nonEmptyParts[] = $part;
16+
}
17+
}
18+
19+
return implode($glue, $nonEmptyParts);
20+
}
21+
922
/**
1023
* The intention is to limit the length of a name.
1124
*

tests/StringUtilTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,33 @@
22

33
namespace MLL\Utils\Tests;
44

5+
use Illuminate\Support\Collection;
56
use MLL\Utils\StringUtil;
67
use PHPUnit\Framework\TestCase;
78

89
final class StringUtilTest extends TestCase
910
{
11+
/**
12+
* @dataProvider joinNonEmpty
13+
*
14+
* @param iterable<string|null> $parts
15+
*/
16+
public function testJoinNonEmpty(string $expectedJoined, string $glue, iterable $parts): void
17+
{
18+
self::assertSame(
19+
$expectedJoined,
20+
StringUtil::joinNonEmpty($glue, $parts)
21+
);
22+
}
23+
24+
/** @return iterable<array{string, string, iterable<string|null>}> */
25+
public static function joinNonEmpty(): iterable
26+
{
27+
yield ['a b', ' ', ['a', null, '', 'b']];
28+
yield ['ab', '', ['a', null, '', 'b']];
29+
yield ['a,b', ',', new Collection(['a', null, '', 'b'])];
30+
}
31+
1032
/** @dataProvider shortenFirstname */
1133
public function testShortenFirstname(string $expectedShortened, string $input): void
1234
{

0 commit comments

Comments
 (0)