2017-01-04 02:10:27 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp;
|
|
|
|
|
2017-04-27 17:51:06 +02:00
|
|
|
final class Producer implements Iterator {
|
2017-01-04 02:10:27 +01:00
|
|
|
use CallableMaker, Internal\Producer;
|
|
|
|
|
|
|
|
/**
|
2017-03-11 06:08:40 +01:00
|
|
|
* @param callable(callable(mixed $value): Promise $emit): \Generator $producer
|
2017-01-04 02:10:27 +01:00
|
|
|
*
|
|
|
|
* @throws \Error Thrown if the callable does not return a Generator.
|
|
|
|
*/
|
|
|
|
public function __construct(callable $producer) {
|
|
|
|
$result = $producer($this->callableFromInstanceMethod("emit"));
|
|
|
|
|
|
|
|
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);
|
|
|
|
$coroutine->onResolve(function ($exception) {
|
|
|
|
if ($this->complete) {
|
|
|
|
return;
|
|
|
|
}
|
2017-01-07 13:47:45 +01:00
|
|
|
|
2017-04-26 19:20:30 +02:00
|
|
|
if ($exception) {
|
|
|
|
$this->fail($exception);
|
|
|
|
return;
|
|
|
|
}
|
2017-01-07 13:47:45 +01:00
|
|
|
|
2017-04-26 19:20:30 +02:00
|
|
|
$this->complete();
|
2017-01-04 02:10:27 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|