1
0
mirror of https://github.com/danog/amp.git synced 2025-01-22 13:21:16 +01:00
amp/lib/Internal/LazyAwaitable.php

54 lines
1.2 KiB
PHP
Raw Normal View History

2016-05-21 09:44:52 -05:00
<?php
2016-08-15 23:46:26 -05:00
declare(strict_types=1);
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-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
}
}