1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace loophp\collection\Operation; |
6
|
|
|
|
7
|
|
|
use Amp\Sync\LocalSemaphore; |
8
|
|
|
use Closure; |
9
|
|
|
use Exception; |
10
|
|
|
use Generator; |
11
|
|
|
|
12
|
|
|
use function Amp\Iterator\fromIterable; |
13
|
|
|
use function Amp\ParallelFunctions\parallel; |
14
|
|
|
use function Amp\Promise\wait; |
15
|
|
|
use function Amp\Sync\ConcurrentIterator\map; |
|
|
|
|
16
|
|
|
use function function_exists; |
17
|
|
|
|
18
|
1 |
|
if (!function_exists('Amp\ParallelFunctions\parallel')) { |
19
|
|
|
throw new Exception('You need amphp/parallel-functions to get this operation working.'); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @immutable |
24
|
|
|
* |
25
|
|
|
* @template TKey |
26
|
|
|
* @template T |
27
|
|
|
*/ |
28
|
|
|
final class AsyncMap extends AbstractOperation |
29
|
|
|
{ |
30
|
|
|
/** |
31
|
|
|
* @template V |
32
|
|
|
* |
33
|
|
|
* @return Closure(callable(T, TKey): V): Closure(iterable<TKey, T>): Generator<TKey, V> |
34
|
|
|
*/ |
35
|
2 |
|
public function __invoke(): Closure |
36
|
|
|
{ |
37
|
2 |
|
return |
38
|
|
|
/** |
39
|
|
|
* @param callable(T, TKey): V $callback |
40
|
|
|
* |
41
|
|
|
* @return Closure(iterable<TKey, T>): Generator<TKey, V> |
42
|
|
|
*/ |
43
|
2 |
|
static fn (callable $callback): Closure => |
44
|
|
|
/** |
45
|
|
|
* @param iterable<TKey, T> $iterable |
46
|
|
|
* |
47
|
|
|
* @return Generator<TKey, V> |
48
|
|
|
*/ |
49
|
2 |
|
static function (iterable $iterable) use ($callback): Generator { |
50
|
2 |
|
$parallelCallBack = |
51
|
|
|
/** |
52
|
|
|
* @param array{0: TKey, 1: T} $value |
53
|
|
|
* |
54
|
|
|
* @return array{0: TKey, 1: V} |
55
|
|
|
*/ |
56
|
2 |
|
static fn (array $value): array => [$value[0], $callback($value[1], $value[0])]; |
57
|
|
|
|
58
|
2 |
|
$iter = map(fromIterable((new Pack())()($iterable)), new LocalSemaphore(32), parallel($parallelCallBack)); |
59
|
|
|
|
60
|
2 |
|
while (wait($iter->advance())) { |
61
|
|
|
/** @var array{0: TKey, 1: V} $item */ |
62
|
2 |
|
$item = $iter->getCurrent(); |
63
|
|
|
|
64
|
2 |
|
yield $item[0] => $item[1]; |
65
|
|
|
} |
66
|
2 |
|
}; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
Let?s assume that you have a directory layout like this:
and let?s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: