2017-01-04 02:10:27 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp;
|
|
|
|
|
2017-01-07 13:47:45 +01:00
|
|
|
use AsyncInterop\Loop;
|
2017-01-04 02:10:27 +01:00
|
|
|
|
|
|
|
final class Producer implements Stream {
|
|
|
|
use CallableMaker, Internal\Producer;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param callable(callable(mixed $value): Promise $emit): \Generator $producer
|
|
|
|
*
|
|
|
|
* @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-01-04 02:10:27 +01:00
|
|
|
Loop::defer(function () use ($result) {
|
|
|
|
$coroutine = new Coroutine($result);
|
|
|
|
$coroutine->when(function ($exception, $value) {
|
|
|
|
if ($this->resolved) {
|
|
|
|
return;
|
|
|
|
}
|
2017-01-07 13:47:45 +01:00
|
|
|
|
2017-01-04 02:10:27 +01:00
|
|
|
if ($exception) {
|
|
|
|
$this->fail($exception);
|
|
|
|
return;
|
|
|
|
}
|
2017-01-07 13:47:45 +01:00
|
|
|
|
2017-01-04 02:10:27 +01:00
|
|
|
$this->resolve($value);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|