2016-12-29 14:09:49 -06:00
|
|
|
<?php
|
2016-08-15 23:46:26 -05:00
|
|
|
|
2016-12-15 18:50:33 -06:00
|
|
|
namespace Amp;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2017-01-07 13:47:45 +01:00
|
|
|
use AsyncInterop\Promise;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2016-06-01 12:18:11 -05:00
|
|
|
/**
|
2016-12-15 18:50:33 -06:00
|
|
|
* Creates a promise that calls $promisor only when the result of the promise is requested (i.e. when() 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 12:18:11 -05:00
|
|
|
*/
|
2016-12-15 18:50:33 -06:00
|
|
|
class Lazy implements Promise {
|
2016-08-17 22:25:54 -05:00
|
|
|
/** @var callable|null */
|
2016-12-15 18:50:33 -06:00
|
|
|
private $promisor;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2017-01-07 13:47:45 +01:00
|
|
|
/** @var \AsyncInterop\Promise|null */
|
2016-11-14 13:59:21 -06:00
|
|
|
private $promise;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
|
|
|
/**
|
2016-12-15 18:50:33 -06:00
|
|
|
* @param callable $promisor Function which starts an async operation, returning a Promise or any value.
|
2016-05-21 09:44:52 -05:00
|
|
|
*/
|
2016-12-15 18:50:33 -06:00
|
|
|
public function __construct(callable $promisor) {
|
|
|
|
$this->promisor = $promisor;
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2016-06-01 12:10:46 -05:00
|
|
|
* {@inheritdoc}
|
2016-05-21 09:44:52 -05:00
|
|
|
*/
|
2016-06-01 12:10:46 -05:00
|
|
|
public function when(callable $onResolved) {
|
2016-12-15 18:50:33 -06:00
|
|
|
if ($this->promise === null) {
|
|
|
|
$provider = $this->promisor;
|
|
|
|
$this->promisor = null;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
|
|
|
try {
|
2016-11-14 13:59:21 -06:00
|
|
|
$this->promise = $provider();
|
2016-05-22 13:42:38 -05:00
|
|
|
|
2016-11-14 14:10:44 -06:00
|
|
|
if (!$this->promise instanceof Promise) {
|
2016-11-14 13:59:21 -06:00
|
|
|
$this->promise = new Success($this->promise);
|
2016-05-22 13:42:38 -05:00
|
|
|
}
|
2016-05-21 09:44:52 -05:00
|
|
|
} catch (\Throwable $exception) {
|
2016-11-14 13:59:21 -06:00
|
|
|
$this->promise = new Failure($exception);
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-14 13:59:21 -06:00
|
|
|
$this->promise->when($onResolved);
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
}
|