Skip to content

Commit 8e99f34

Browse files
committed
Added method join and wraps
1 parent 67323e8 commit 8e99f34

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

src/Helper.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,49 @@ public static function snakeCase(string $value, string $delimiter = '_'): string
203203

204204
return $value;
205205
}
206+
207+
/**
208+
* Join string[] to string with given $separator and $lastSeparator.
209+
*
210+
* @param array $pieces
211+
* @param string $separator
212+
* @param string|null $lastSeparator
213+
* @return string
214+
*/
215+
public static function join(array $pieces, string $separator, string $lastSeparator = null): string
216+
{
217+
if (is_null($lastSeparator)) {
218+
$lastSeparator = $separator;
219+
}
220+
221+
$last = array_pop($pieces);
222+
223+
switch (count($pieces)) {
224+
case 0:
225+
return $last ?: '';
226+
case 1:
227+
return $pieces[0] . $lastSeparator . $last;
228+
default:
229+
return implode($separator, $pieces) . $lastSeparator . $last;
230+
}
231+
}
232+
233+
/**
234+
* Wrap string[] by given $prefix and $suffix
235+
*
236+
* @param array $strings
237+
* @param string $prefix
238+
* @param string|null $suffix
239+
* @return array
240+
*/
241+
public static function wraps(array $strings, string $prefix, string $suffix = null): array
242+
{
243+
if (is_null($suffix)) {
244+
$suffix = $prefix;
245+
}
246+
247+
return array_map(function ($str) use ($prefix, $suffix) {
248+
return $prefix . $str . $suffix;
249+
}, $strings);
250+
}
206251
}

tests/HelperTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,28 @@ public function testArrayUnset()
131131
'message' => "lorem ipsum",
132132
]);
133133
}
134+
135+
public function testJoin()
136+
{
137+
$pieces0 = [];
138+
$pieces1 = [1];
139+
$pieces2 = [1, 2];
140+
$pieces3 = [1, 2, 3];
141+
142+
$separator = ', ';
143+
$lastSeparator = ', and ';
144+
145+
$this->assertEquals(Helper::join($pieces0, $separator, $lastSeparator), '');
146+
$this->assertEquals(Helper::join($pieces1, $separator, $lastSeparator), '1');
147+
$this->assertEquals(Helper::join($pieces2, $separator, $lastSeparator), '1, and 2');
148+
$this->assertEquals(Helper::join($pieces3, $separator, $lastSeparator), '1, 2, and 3');
149+
}
150+
151+
public function testWraps()
152+
{
153+
$inputs = [1, 2, 3];
154+
155+
$this->assertEquals(Helper::wraps($inputs, '-'), ['-1-', '-2-', '-3-']);
156+
$this->assertEquals(Helper::wraps($inputs, '-', '+'), ['-1+', '-2+', '-3+']);
157+
}
134158
}

0 commit comments

Comments
 (0)