2016-05-21 09:44:52 -05:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp\Awaitable\Internal;
|
|
|
|
|
2016-05-22 13:42:38 -05:00
|
|
|
use Amp\Awaitable\Failure;
|
|
|
|
use Amp\Awaitable\Success;
|
|
|
|
use Interop\Async\Awaitable;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2016-05-21 23:47:50 -05:00
|
|
|
class LazyAwaitable implements \Interop\Async\Awaitable {
|
2016-05-21 09:44:52 -05:00
|
|
|
/**
|
|
|
|
* @var callable|null
|
|
|
|
*/
|
|
|
|
private $provider;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var \Interop\Async\Awaitable
|
|
|
|
*/
|
|
|
|
private $awaitable;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param callable $provider
|
|
|
|
*/
|
|
|
|
public function __construct(callable $provider) {
|
|
|
|
$this->provider = $provider;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return \Interop\Async\Awaitable
|
|
|
|
*/
|
|
|
|
protected function getAwaitable() {
|
|
|
|
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
|
|
|
} catch (\Exception $exception) {
|
2016-05-22 13:42:38 -05:00
|
|
|
$this->awaitable = new Failure($exception);
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this->awaitable;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
|
|
|
public function when(callable $onResolved) {
|
|
|
|
$this->getAwaitable()->when($onResolved);
|
|
|
|
}
|
|
|
|
}
|