Skip to content

Commit 72d8f08

Browse files
milodg
authored andcommitted
Arrays: added wrap() method (#180)
1 parent 2bc2f58 commit 72d8f08

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/Utils/Arrays.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,4 +401,19 @@ public static function toKey($value)
401401
{
402402
return key([$value => null]);
403403
}
404+
405+
406+
/**
407+
* Returns copy of the $array where every item is converted to string
408+
* and prefixed by $prefix and suffixed by $suffix.
409+
* @return string[]
410+
*/
411+
public static function wrap(array $array, string $prefix = '', string $suffix = ''): array
412+
{
413+
$res = [];
414+
foreach ($array as $k => $v) {
415+
$res[$k] = $prefix . $v . $suffix;
416+
}
417+
return $res;
418+
}
404419
}

tests/Utils/Arrays.wrap().phpt

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\Arrays::wrap()
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Utils\Arrays;
10+
use Tester\Assert;
11+
12+
13+
require __DIR__ . '/../bootstrap.php';
14+
15+
16+
test('Basics', function () {
17+
Assert::same([], Arrays::wrap([], '{', '}'));
18+
Assert::same(['STR'], Arrays::wrap(['STR']));
19+
Assert::same(['{STR'], Arrays::wrap(['STR'], '{'));
20+
Assert::same(['STR}'], Arrays::wrap(['STR'], '', '}'));
21+
Assert::same(['{STR}'], Arrays::wrap(['STR'], '{', '}'));
22+
});
23+
24+
25+
test('Type conversion', function () {
26+
$o = new class {
27+
public function __toString()
28+
{
29+
return 'toString';
30+
}
31+
};
32+
33+
$cases = [
34+
[0, '0'],
35+
[1.1, '1.1'],
36+
[null, ''],
37+
[false, ''],
38+
[true, '1'],
39+
[$o, 'toString'],
40+
];
41+
Assert::same(array_column($cases, 1), Arrays::wrap(array_column($cases, 0)));
42+
43+
Assert::error(function () {
44+
Arrays::wrap([[]]);
45+
}, E_NOTICE, 'Array to string conversion');
46+
});

0 commit comments

Comments
 (0)