Skip to content

Commit ff63fa0

Browse files
committed
added Array::invoke() & invokeMethod()
1 parent 0e371f6 commit ff63fa0

File tree

3 files changed

+97
-0
lines changed

3 files changed

+97
-0
lines changed

src/Utils/Arrays.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,34 @@ public static function map(array $array, callable $callback): array
320320
}
321321

322322

323+
/**
324+
* Invokes all callbacks and returns array of results.
325+
* @param callable[] $callbacks
326+
*/
327+
public static function invoke(iterable $callbacks, ...$args): array
328+
{
329+
$res = [];
330+
foreach ($callbacks as $k => $cb) {
331+
$res[$k] = $cb(...$args);
332+
}
333+
return $res;
334+
}
335+
336+
337+
/**
338+
* Invokes method on every object in an array and returns array of results.
339+
* @param object[] $objects
340+
*/
341+
public static function invokeMethod(array $objects, string $method, ...$args): array
342+
{
343+
$res = [];
344+
foreach ($objects as $k => $obj) {
345+
$res[$k] = $obj->$method(...$args);
346+
}
347+
return $res;
348+
}
349+
350+
323351
/**
324352
* Copies the elements of the $array array to the $object object and then returns it.
325353
* @param object $object

tests/Utils/Arrays.invoke.phpt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Utils\Arrays;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
class Test
13+
{
14+
public function fn1(...$args)
15+
{
16+
return __METHOD__ . ' ' . implode(',', $args);
17+
}
18+
19+
20+
public function fn2(...$args)
21+
{
22+
return __METHOD__ . ' ' . implode(',', $args);
23+
}
24+
}
25+
26+
27+
$list = [];
28+
$list[] = [new Test, 'fn1'];
29+
$list['key'] = [new Test, 'fn2'];
30+
31+
Assert::same(
32+
['Test::fn1 a,b', 'key' => 'Test::fn2 a,b'],
33+
Arrays::invoke($list, 'a', 'b')
34+
);
35+
36+
Assert::same(
37+
['Test::fn1 a,b', 'key' => 'Test::fn2 a,b'],
38+
Arrays::invoke(new ArrayIterator($list), 'a', 'b')
39+
);
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Utils\Arrays;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
class Test1
13+
{
14+
public function fn(...$args)
15+
{
16+
return static::class . ' ' . implode(',', $args);
17+
}
18+
}
19+
20+
class Test2 extends Test1
21+
{
22+
}
23+
24+
25+
$list = [new Test1, 'key' => new Test2];
26+
27+
Assert::same(
28+
['Test1 a,b', 'key' => 'Test2 a,b'],
29+
Arrays::invokeMethod($list, 'fn', 'a', 'b')
30+
);

0 commit comments

Comments
 (0)