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

47 lines
1.2 KiB
PHP
Raw Normal View History

<?php
2016-08-15 23:46:26 -05:00
namespace Amp;
2016-05-21 09:44:52 -05:00
use AsyncInterop\Promise;
2016-05-21 09:44:52 -05:00
2016-06-01 12:18:11 -05:00
/**
* Creates a promise that calls $promisor only when the result of the promise is requested (i.e. when() is called on
* the promise). $promisor can return a promise or any value. If $promisor throws an exception, the promise fails with
* that exception.
2016-06-01 12:18:11 -05:00
*/
class Lazy implements Promise {
2016-08-17 22:25:54 -05:00
/** @var callable|null */
private $promisor;
2016-05-21 09:44:52 -05:00
/** @var \AsyncInterop\Promise|null */
2016-11-14 13:59:21 -06:00
private $promise;
2016-05-21 09:44:52 -05:00
/**
* @param callable $promisor Function which starts an async operation, returning a Promise or any value.
2016-05-21 09:44:52 -05:00
*/
public function __construct(callable $promisor) {
$this->promisor = $promisor;
2016-05-21 09:44:52 -05:00
}
/**
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) {
if ($this->promise === null) {
$provider = $this->promisor;
$this->promisor = null;
2016-05-21 09:44:52 -05:00
try {
2016-11-14 13:59:21 -06:00
$this->promise = $provider();
2016-05-22 13:42:38 -05:00
2016-11-14 14:10:44 -06:00
if (!$this->promise instanceof Promise) {
2016-11-14 13:59:21 -06:00
$this->promise = new Success($this->promise);
2016-05-22 13:42:38 -05:00
}
2016-05-21 09:44:52 -05:00
} catch (\Throwable $exception) {
2016-11-14 13:59:21 -06:00
$this->promise = new Failure($exception);
2016-05-21 09:44:52 -05:00
}
}
2016-11-14 13:59:21 -06:00
$this->promise->when($onResolved);
2016-05-21 09:44:52 -05:00
}
}