2014-09-22 22:47:48 +02:00
|
|
|
<?php
|
|
|
|
|
2014-09-23 04:38:32 +02:00
|
|
|
namespace Amp;
|
2014-09-22 22:47:48 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A placeholder value that will be resolved at some point in the future by
|
|
|
|
* the Promisor that created it.
|
|
|
|
*/
|
|
|
|
class Unresolved implements Promise {
|
|
|
|
private $isResolved = false;
|
|
|
|
private $watchers = [];
|
|
|
|
private $whens = [];
|
|
|
|
private $error;
|
|
|
|
private $result;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Notify the $func callback when the promise resolves (whether successful or not)
|
|
|
|
*/
|
2015-03-19 16:14:21 +01:00
|
|
|
public function when(callable $func): Unresolved {
|
2014-09-22 22:47:48 +02:00
|
|
|
if ($this->isResolved) {
|
|
|
|
$func($this->error, $this->result);
|
|
|
|
} else {
|
|
|
|
$this->whens[] = $func;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Notify the $func callback when resolution progress events are emitted
|
|
|
|
*/
|
2015-03-19 16:14:21 +01:00
|
|
|
public function watch(callable $func): Unresolved {
|
2014-09-22 22:47:48 +02:00
|
|
|
if (!$this->isResolved) {
|
|
|
|
$this->watchers[] = $func;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2015-03-18 19:04:18 +01:00
|
|
|
protected function resolve(\Exception $error = null, $result = null) {
|
2014-09-22 22:47:48 +02:00
|
|
|
if ($this->isResolved) {
|
|
|
|
throw new \LogicException(
|
|
|
|
'Promise already resolved'
|
|
|
|
);
|
|
|
|
} elseif ($result === $this) {
|
|
|
|
throw new \LogicException(
|
|
|
|
'A Promise cannot act as its own resolution result'
|
|
|
|
);
|
|
|
|
} elseif ($result instanceof Promise) {
|
|
|
|
$result->when(function($error, $result) {
|
|
|
|
$this->resolve($error, $result);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
$this->isResolved = true;
|
|
|
|
$this->error = $error;
|
|
|
|
$this->result = $result;
|
|
|
|
foreach ($this->whens as $when) {
|
|
|
|
$when($error, $result);
|
|
|
|
}
|
|
|
|
$this->whens = $this->watchers = [];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-03-18 19:04:18 +01:00
|
|
|
protected function update($progress) {
|
2014-09-22 22:47:48 +02:00
|
|
|
if ($this->isResolved) {
|
|
|
|
throw new \LogicException(
|
|
|
|
'Cannot update resolved promise'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
foreach ($this->watchers as $watcher) {
|
|
|
|
$watcher($progress);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|