1
0
mirror of https://github.com/danog/amp.git synced 2024-11-27 12:35:02 +01:00
amp/lib/Internal/LazyAwaitable.php

50 lines
1.1 KiB
PHP
Raw Normal View History

2016-05-21 16:44:52 +02:00
<?php
2016-05-24 05:48:28 +02:00
namespace Amp\Internal;
2016-05-21 16:44:52 +02:00
2016-05-24 05:48:28 +02:00
use Amp\Failure;
use Amp\Success;
2016-05-22 20:42:38 +02:00
use Interop\Async\Awaitable;
2016-05-21 16:44:52 +02:00
2016-05-24 17:39:19 +02:00
class LazyAwaitable implements Awaitable {
2016-05-21 16:44:52 +02:00
/**
* @var callable|null
*/
private $provider;
/**
2016-06-01 19:10:46 +02:00
* @var \Interop\Async\Awaitable|null
2016-05-21 16:44:52 +02:00
*/
private $awaitable;
/**
* @param callable $provider
*/
public function __construct(callable $provider) {
$this->provider = $provider;
}
/**
2016-06-01 19:10:46 +02:00
* {@inheritdoc}
2016-05-21 16:44:52 +02:00
*/
2016-06-01 19:10:46 +02:00
public function when(callable $onResolved) {
2016-05-21 16:44:52 +02:00
if (null === $this->awaitable) {
$provider = $this->provider;
$this->provider = null;
try {
2016-05-22 20:42:38 +02:00
$this->awaitable = $provider();
if ($this->awaitable instanceof Awaitable) {
$this->awaitable = new Success($this->awaitable);
}
2016-05-21 16:44:52 +02:00
} catch (\Throwable $exception) {
2016-05-22 20:42:38 +02:00
$this->awaitable = new Failure($exception);
2016-05-21 16:44:52 +02:00
} catch (\Exception $exception) {
2016-05-22 20:42:38 +02:00
$this->awaitable = new Failure($exception);
2016-05-21 16:44:52 +02:00
}
}
2016-06-01 19:10:46 +02:00
$this->awaitable->when($onResolved);
2016-05-21 16:44:52 +02:00
}
}