2016-12-29 21:09:49 +01:00
|
|
|
<?php
|
2016-08-16 06:46:26 +02:00
|
|
|
|
2016-12-16 01:50:33 +01:00
|
|
|
namespace Amp;
|
2016-05-21 16:44:52 +02:00
|
|
|
|
2017-02-20 21:53:58 +01:00
|
|
|
use React\Promise\PromiseInterface as ReactPromise;
|
|
|
|
|
2016-06-01 19:18:11 +02:00
|
|
|
/**
|
2017-03-21 17:23:37 +01:00
|
|
|
* Creates a promise that calls $promisor only when the result of the promise is requested (i.e. onResolve() is called
|
|
|
|
* on the promise). $promisor can return a promise or any value. If $promisor throws an exception, the promise fails
|
|
|
|
* with that exception.
|
2016-06-01 19:18:11 +02:00
|
|
|
*/
|
2017-01-08 08:02:11 +01:00
|
|
|
class LazyPromise implements Promise {
|
2016-08-18 05:25:54 +02:00
|
|
|
/** @var callable|null */
|
2016-12-16 01:50:33 +01:00
|
|
|
private $promisor;
|
2016-05-21 16:44:52 +02:00
|
|
|
|
2017-03-10 21:58:46 +01:00
|
|
|
/** @var \Amp\Promise|null */
|
2016-11-14 20:59:21 +01:00
|
|
|
private $promise;
|
2016-05-21 16:44:52 +02:00
|
|
|
|
|
|
|
/**
|
2016-12-16 01:50:33 +01:00
|
|
|
* @param callable $promisor Function which starts an async operation, returning a Promise or any value.
|
2016-05-21 16:44:52 +02:00
|
|
|
*/
|
2016-12-16 01:50:33 +01:00
|
|
|
public function __construct(callable $promisor) {
|
|
|
|
$this->promisor = $promisor;
|
2016-05-21 16:44:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2016-06-01 19:10:46 +02:00
|
|
|
* {@inheritdoc}
|
2016-05-21 16:44:52 +02:00
|
|
|
*/
|
2017-03-21 17:23:37 +01:00
|
|
|
public function onResolve(callable $onResolved) {
|
2016-12-16 01:50:33 +01:00
|
|
|
if ($this->promise === null) {
|
|
|
|
$provider = $this->promisor;
|
|
|
|
$this->promisor = null;
|
2016-05-21 16:44:52 +02:00
|
|
|
|
|
|
|
try {
|
2016-11-14 20:59:21 +01:00
|
|
|
$this->promise = $provider();
|
2016-05-22 20:42:38 +02:00
|
|
|
|
2017-03-28 01:37:55 +02:00
|
|
|
if ($this->promise instanceof \Generator) {
|
|
|
|
$this->promise = new Coroutine($this->promise);
|
|
|
|
} elseif ($this->promise instanceof ReactPromise) {
|
2017-03-15 17:12:49 +01:00
|
|
|
$this->promise = Promise\adapt($this->promise);
|
2017-03-28 01:37:55 +02:00
|
|
|
} elseif (!$this->promise instanceof Promise) {
|
2016-11-14 20:59:21 +01:00
|
|
|
$this->promise = new Success($this->promise);
|
2016-05-22 20:42:38 +02:00
|
|
|
}
|
2016-05-21 16:44:52 +02:00
|
|
|
} catch (\Throwable $exception) {
|
2016-11-14 20:59:21 +01:00
|
|
|
$this->promise = new Failure($exception);
|
2016-05-21 16:44:52 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-03-21 17:23:37 +01:00
|
|
|
$this->promise->onResolve($onResolved);
|
2016-05-21 16:44:52 +02:00
|
|
|
}
|
2017-04-24 15:39:08 +02:00
|
|
|
}
|