2016-08-17 22:25:54 -05:00
|
|
|
<?php declare(strict_types = 1);
|
2016-08-15 23:46:26 -05:00
|
|
|
|
2016-05-23 22:48:28 -05:00
|
|
|
namespace Amp\Internal;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2016-08-16 13:07:51 -05:00
|
|
|
use Amp\{ Failure, Success };
|
2016-11-14 13:59:21 -06:00
|
|
|
use Interop\Async\Promise;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2016-06-01 12:18:11 -05:00
|
|
|
/**
|
2016-11-14 13:59:21 -06:00
|
|
|
* Promise returned from Amp\lazy(). Use Amp\lazy() instead of instigating this object directly.
|
2016-06-01 12:18:11 -05:00
|
|
|
*
|
|
|
|
* @internal
|
|
|
|
*/
|
2016-11-14 13:59:21 -06:00
|
|
|
class LazyPromise implements Promise {
|
2016-08-17 22:25:54 -05:00
|
|
|
/** @var callable|null */
|
2016-05-21 09:44:52 -05:00
|
|
|
private $provider;
|
|
|
|
|
2016-11-14 13:59:21 -06:00
|
|
|
/** @var \Interop\Async\Promise|null */
|
|
|
|
private $promise;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param callable $provider
|
|
|
|
*/
|
|
|
|
public function __construct(callable $provider) {
|
|
|
|
$this->provider = $provider;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
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-11-14 13:59:21 -06:00
|
|
|
if (null === $this->promise) {
|
2016-05-21 09:44:52 -05:00
|
|
|
$provider = $this->provider;
|
|
|
|
$this->provider = null;
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|