Skip to content

Commit

Permalink
Add StringUtil::joinNonEmpty()
Browse files Browse the repository at this point in the history
  • Loading branch information
spawnia authored Jan 12, 2024
1 parent 075f157 commit e01de9b
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 3 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
},
Expand Down
13 changes: 13 additions & 0 deletions src/StringUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@

final class StringUtil
{
/** @param iterable<string|null> $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.
*
Expand Down
22 changes: 22 additions & 0 deletions tests/StringUtilTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string|null> $parts
*/
public function testJoinNonEmpty(string $expectedJoined, string $glue, iterable $parts): void
{
self::assertSame(
$expectedJoined,
StringUtil::joinNonEmpty($glue, $parts)
);
}

/** @return iterable<array{string, string, iterable<string|null>}> */
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
{
Expand Down

0 comments on commit e01de9b

Please sign in to comment.