2016-05-21 09:44:52 -05:00
|
|
|
<?php
|
|
|
|
|
2016-05-23 22:48:28 -05:00
|
|
|
namespace Amp\Internal;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2016-05-23 22:48:28 -05:00
|
|
|
use Amp\Failure;
|
|
|
|
use Amp\Success;
|
2016-05-22 13:42:38 -05:00
|
|
|
use Interop\Async\Awaitable;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2016-06-01 12:18:11 -05:00
|
|
|
/**
|
|
|
|
* Awaitable returned from Amp\lazy(). Use Amp\lazy() instead of instigating this object directly.
|
|
|
|
*
|
|
|
|
* @internal
|
|
|
|
*/
|
2016-05-24 10:39:19 -05:00
|
|
|
class LazyAwaitable implements Awaitable {
|
2016-05-21 09:44:52 -05:00
|
|
|
/**
|
|
|
|
* @var callable|null
|
|
|
|
*/
|
|
|
|
private $provider;
|
|
|
|
|
|
|
|
/**
|
2016-06-01 12:10:46 -05:00
|
|
|
* @var \Interop\Async\Awaitable|null
|
2016-05-21 09:44:52 -05:00
|
|
|
*/
|
|
|
|
private $awaitable;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @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-05-21 09:44:52 -05:00
|
|
|
if (null === $this->awaitable) {
|
|
|
|
$provider = $this->provider;
|
|
|
|
$this->provider = null;
|
|
|
|
|
|
|
|
try {
|
2016-05-22 13:42:38 -05:00
|
|
|
$this->awaitable = $provider();
|
|
|
|
|
|
|
|
if ($this->awaitable instanceof Awaitable) {
|
|
|
|
$this->awaitable = new Success($this->awaitable);
|
|
|
|
}
|
2016-05-21 09:44:52 -05:00
|
|
|
} catch (\Throwable $exception) {
|
2016-05-22 13:42:38 -05:00
|
|
|
$this->awaitable = new Failure($exception);
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-01 12:10:46 -05:00
|
|
|
$this->awaitable->when($onResolved);
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
}
|