1
0
mirror of https://github.com/danog/amp.git synced 2025-01-22 21:31:18 +01:00
amp/lib/Internal/LazyAwaitable.php
2016-08-17 22:25:54 -05:00

48 lines
1.1 KiB
PHP

<?php declare(strict_types = 1);
namespace Amp\Internal;
use Amp\{ Failure, Success };
use Interop\Async\Awaitable;
/**
* Awaitable returned from Amp\lazy(). Use Amp\lazy() instead of instigating this object directly.
*
* @internal
*/
class LazyAwaitable implements Awaitable {
/** @var callable|null */
private $provider;
/** @var \Interop\Async\Awaitable|null */
private $awaitable;
/**
* @param callable $provider
*/
public function __construct(callable $provider) {
$this->provider = $provider;
}
/**
* {@inheritdoc}
*/
public function when(callable $onResolved) {
if (null === $this->awaitable) {
$provider = $this->provider;
$this->provider = null;
try {
$this->awaitable = $provider();
if ($this->awaitable instanceof Awaitable) {
$this->awaitable = new Success($this->awaitable);
}
} catch (\Throwable $exception) {
$this->awaitable = new Failure($exception);
}
}
$this->awaitable->when($onResolved);
}
}