From e01de9bec783545ed31ef9ad58112f28b39b2075 Mon Sep 17 00:00:00 2001 From: Benedikt Franke Date: Fri, 12 Jan 2024 16:01:34 +0100 Subject: [PATCH] Add `StringUtil::joinNonEmpty()` --- CHANGELOG.md | 6 ++++++ composer.json | 6 +++--- src/StringUtil.php | 13 +++++++++++++ tests/StringUtilTest.php | 22 ++++++++++++++++++++++ 4 files changed, 44 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c158497..5e903e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ See [GitHub releases](https://github.com/mll-lab/php-utils/releases). ## Unreleased +## v1.9.0 + +### Added + +- Add `StringUtil::joinNonEmpty()` + ## v1.8.1 ### Changed diff --git a/composer.json b/composer.json index 0f5e44e..1ec4f98 100644 --- a/composer.json +++ b/composer.json @@ -52,10 +52,10 @@ }, "config": { "allow-plugins": { - "ocramius/package-versions": true, - "phpstan/extension-installer": true, "ergebnis/composer-normalize": true, - "infection/extension-installer": true + "infection/extension-installer": true, + "ocramius/package-versions": true, + "phpstan/extension-installer": true }, "sort-packages": true }, diff --git a/src/StringUtil.php b/src/StringUtil.php index d4cca00..c2abd75 100644 --- a/src/StringUtil.php +++ b/src/StringUtil.php @@ -6,6 +6,19 @@ final class StringUtil { + /** @param iterable $parts */ + public static function joinNonEmpty(string $glue, iterable $parts): string + { + $nonEmptyParts = []; + foreach ($parts as $part) { + if ($part !== '' && $part !== null) { + $nonEmptyParts[] = $part; + } + } + + return implode($glue, $nonEmptyParts); + } + /** * The intention is to limit the length of a name. * diff --git a/tests/StringUtilTest.php b/tests/StringUtilTest.php index 8409f1f..7d56b98 100644 --- a/tests/StringUtilTest.php +++ b/tests/StringUtilTest.php @@ -2,11 +2,33 @@ namespace MLL\Utils\Tests; +use Illuminate\Support\Collection; use MLL\Utils\StringUtil; use PHPUnit\Framework\TestCase; final class StringUtilTest extends TestCase { + /** + * @dataProvider joinNonEmpty + * + * @param iterable $parts + */ + public function testJoinNonEmpty(string $expectedJoined, string $glue, iterable $parts): void + { + self::assertSame( + $expectedJoined, + StringUtil::joinNonEmpty($glue, $parts) + ); + } + + /** @return iterable}> */ + public static function joinNonEmpty(): iterable + { + yield ['a b', ' ', ['a', null, '', 'b']]; + yield ['ab', '', ['a', null, '', 'b']]; + yield ['a,b', ',', new Collection(['a', null, '', 'b'])]; + } + /** @dataProvider shortenFirstname */ public function testShortenFirstname(string $expectedShortened, string $input): void {