| 1 |
<?php |
| 2 |
|
| 3 |
namespace Amp; |
| 4 |
|
| 5 |
/** |
| 6 |
* Emitter is a container for an iterator that can emit values using the emit() method and completed using the |
| 7 |
* complete() and fail() methods of this object. The contained iterator may be accessed using the iterate() |
| 8 |
* method. This object should not be part of a public API, but used internally to create and emit values to an |
| 9 |
* iterator. |
| 10 |
* |
| 11 |
* @template TValue |
| 12 |
*/ |
| 13 |
final class Emitter |
| 14 |
{ |
| 15 |
/** @var Iterator<TValue> Has public emit, complete, and fail methods. */ |
| 16 |
private $emitter; |
| 17 |
|
| 18 |
/** @var Iterator<TValue> Hides producer methods. */ |
| 19 |
private $iterator; |
| 20 |
|
| 21 |
public function __construct() |
| 22 |
{ |
| 23 |
$this->emitter = new class implements Iterator { |
| 24 |
use Internal\Producer { |
| 25 |
emit as public; |
| 26 |
complete as public; |
| 27 |
fail as public; |
| 28 |
} |
| 29 |
}; |
| 30 |
|
| 31 |
$this->iterator = new Internal\PrivateIterator($this->emitter); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* @return Iterator |
| 36 |
* @psalm-return Iterator<TValue> |
| 37 |
*/ |
| 38 |
public function iterate(): Iterator |
| 39 |
{ |
| 40 |
return $this->iterator; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Emits a value to the iterator. |
| 45 |
* |
| 46 |
* @param mixed $value |
| 47 |
* |
| 48 |
* @psalm-param TValue $value |
| 49 |
* |
| 50 |
* @return Promise |
| 51 |
* @psalm-return Promise<null> |
| 52 |
* @psalm-suppress MixedInferredReturnType |
| 53 |
* @psalm-suppress MixedReturnStatement |
| 54 |
*/ |
| 55 |
public function emit($value): Promise |
| 56 |
{ |
| 57 |
/** @psalm-suppress UndefinedInterfaceMethod */ |
| 58 |
return $this->emitter->emit($value); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Completes the iterator. |
| 63 |
* |
| 64 |
* @return void |
| 65 |
*/ |
| 66 |
public function complete() |
| 67 |
{ |
| 68 |
/** @psalm-suppress UndefinedInterfaceMethod */ |
| 69 |
$this->emitter->complete(); |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* Fails the iterator with the given reason. |
| 74 |
* |
| 75 |
* @param \Throwable $reason |
| 76 |
* |
| 77 |
* @return void |
| 78 |
*/ |
| 79 |
public function fail(\Throwable $reason) |
| 80 |
{ |
| 81 |
/** @psalm-suppress UndefinedInterfaceMethod */ |
| 82 |
$this->emitter->fail($reason); |
| 83 |
} |
| 84 |
} |
| 85 |
|