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
|
|
|
|
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
|
2020-10-30 16:36:19 +01:00
|
|
|
* with that exception.
|
2016-06-01 19:18:11 +02:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
final 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
|
|
|
|
2020-03-28 21:55:44 +01:00
|
|
|
/** @var Promise|null */
|
2020-09-27 05:26:52 +02:00
|
|
|
private ?Promise $promise;
|
2016-05-21 16:44:52 +02:00
|
|
|
|
|
|
|
/**
|
2017-06-09 17:18:06 +02:00
|
|
|
* @param callable $promisor Function which starts an async operation, returning a Promise (or any value).
|
|
|
|
* Generators will be run as a coroutine.
|
2016-05-21 16:44:52 +02:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
public function __construct(callable $promisor)
|
|
|
|
{
|
2016-12-16 01:50:33 +01:00
|
|
|
$this->promisor = $promisor;
|
2016-05-21 16:44:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-09-27 05:26:52 +02:00
|
|
|
* @inheritDoc
|
2016-05-21 16:44:52 +02:00
|
|
|
*/
|
2020-09-24 18:52:22 +02:00
|
|
|
public function onResolve(callable $onResolved): void
|
2018-06-18 20:00:01 +02:00
|
|
|
{
|
2020-09-27 05:26:52 +02:00
|
|
|
if (!isset($this->promise)) {
|
2020-03-28 21:55:44 +01:00
|
|
|
\assert($this->promisor !== null);
|
|
|
|
|
2016-12-16 01:50:33 +01:00
|
|
|
$provider = $this->promisor;
|
|
|
|
$this->promisor = null;
|
2020-10-30 16:36:19 +01:00
|
|
|
$this->promise = async($provider);
|
2016-05-21 16:44:52 +02:00
|
|
|
}
|
|
|
|
|
2020-03-28 21:55:44 +01:00
|
|
|
\assert($this->promise !== null);
|
|
|
|
|
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
|
|
|
}
|