Skip to content

Commit

Permalink
Added method join and wraps
Browse files Browse the repository at this point in the history
  • Loading branch information
emsifa committed Nov 27, 2018
1 parent 67323e8 commit 8e99f34
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,49 @@ public static function snakeCase(string $value, string $delimiter = '_'): string

return $value;
}

/**
* Join string[] to string with given $separator and $lastSeparator.
*
* @param array $pieces
* @param string $separator
* @param string|null $lastSeparator
* @return string
*/
public static function join(array $pieces, string $separator, string $lastSeparator = null): string
{
if (is_null($lastSeparator)) {
$lastSeparator = $separator;
}

$last = array_pop($pieces);

switch (count($pieces)) {
case 0:
return $last ?: '';
case 1:
return $pieces[0] . $lastSeparator . $last;
default:
return implode($separator, $pieces) . $lastSeparator . $last;
}
}

/**
* Wrap string[] by given $prefix and $suffix
*
* @param array $strings
* @param string $prefix
* @param string|null $suffix
* @return array
*/
public static function wraps(array $strings, string $prefix, string $suffix = null): array
{
if (is_null($suffix)) {
$suffix = $prefix;
}

return array_map(function ($str) use ($prefix, $suffix) {
return $prefix . $str . $suffix;
}, $strings);
}
}
24 changes: 24 additions & 0 deletions tests/HelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,28 @@ public function testArrayUnset()
'message' => "lorem ipsum",
]);
}

public function testJoin()
{
$pieces0 = [];
$pieces1 = [1];
$pieces2 = [1, 2];
$pieces3 = [1, 2, 3];

$separator = ', ';
$lastSeparator = ', and ';

$this->assertEquals(Helper::join($pieces0, $separator, $lastSeparator), '');
$this->assertEquals(Helper::join($pieces1, $separator, $lastSeparator), '1');
$this->assertEquals(Helper::join($pieces2, $separator, $lastSeparator), '1, and 2');
$this->assertEquals(Helper::join($pieces3, $separator, $lastSeparator), '1, 2, and 3');
}

public function testWraps()
{
$inputs = [1, 2, 3];

$this->assertEquals(Helper::wraps($inputs, '-'), ['-1-', '-2-', '-3-']);
$this->assertEquals(Helper::wraps($inputs, '-', '+'), ['-1+', '-2+', '-3+']);
}
}

0 comments on commit 8e99f34

Please sign in to comment.