2017-01-04 02:10:27 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp;
|
|
|
|
|
2020-03-28 14:25:39 +01:00
|
|
|
/**
|
|
|
|
* @template-covariant TValue
|
|
|
|
* @template-implements Iterator<TValue>
|
2020-05-13 17:15:21 +02:00
|
|
|
*
|
|
|
|
* @deprecated Use {@see AsyncGenerator} instead.
|
|
|
|
*
|
|
|
|
* @psalm-suppress DeprecatedInterface
|
2020-03-28 14:25:39 +01:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
final class Producer implements Iterator
|
|
|
|
{
|
2020-09-27 06:14:17 +02:00
|
|
|
private Internal\Producer $producer;
|
2017-01-04 02:10:27 +01:00
|
|
|
|
|
|
|
/**
|
2020-03-28 14:32:53 +01:00
|
|
|
* @param callable(callable(TValue):Promise):\Generator $producer
|
2017-01-04 02:10:27 +01:00
|
|
|
*
|
|
|
|
* @throws \Error Thrown if the callable does not return a Generator.
|
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
public function __construct(callable $producer)
|
|
|
|
{
|
2020-09-27 06:14:17 +02:00
|
|
|
$this->producer = $emitter = new Internal\Producer;
|
|
|
|
|
|
|
|
$result = $producer(\Closure::fromCallable([$this->producer, 'emit']));
|
2017-01-04 02:10:27 +01:00
|
|
|
|
|
|
|
if (!$result instanceof \Generator) {
|
|
|
|
throw new \Error("The callable did not return a Generator");
|
|
|
|
}
|
2017-01-07 13:47:45 +01:00
|
|
|
|
2017-04-26 19:20:30 +02:00
|
|
|
$coroutine = new Coroutine($result);
|
2020-09-27 06:14:17 +02:00
|
|
|
$coroutine->onResolve(static function ($exception) use ($emitter): void {
|
|
|
|
if ($emitter->isComplete()) {
|
2017-04-26 19:20:30 +02:00
|
|
|
return;
|
|
|
|
}
|
2017-01-07 13:47:45 +01:00
|
|
|
|
2017-04-26 19:20:30 +02:00
|
|
|
if ($exception) {
|
2020-09-27 06:14:17 +02:00
|
|
|
$emitter->fail($exception);
|
2017-04-26 19:20:30 +02:00
|
|
|
return;
|
|
|
|
}
|
2017-01-07 13:47:45 +01:00
|
|
|
|
2020-09-27 06:14:17 +02:00
|
|
|
$emitter->complete();
|
2017-01-04 02:10:27 +01:00
|
|
|
});
|
|
|
|
}
|
2020-09-27 06:14:17 +02:00
|
|
|
|
|
|
|
public function advance(): Promise
|
|
|
|
{
|
|
|
|
return $this->producer->advance();
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getCurrent()
|
|
|
|
{
|
|
|
|
return $this->producer->getCurrent();
|
|
|
|
}
|
2017-01-04 02:10:27 +01:00
|
|
|
}
|