1
0
mirror of https://github.com/danog/amp.git synced 2024-12-12 01:19:46 +01:00
amp/lib/Unresolved.php

82 lines
2.1 KiB
PHP
Raw Normal View History

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;
/**
2015-04-30 19:41:14 +02:00
* Notify the $func callback when the promise resolves (whether successful or not)
*
* @param callable $func
* @return self
2014-09-22 22:47:48 +02:00
*/
2015-04-30 19:41:14 +02:00
public function when(callable $func) {
2014-09-22 22:47:48 +02:00
if ($this->isResolved) {
2015-04-30 19:41:14 +02:00
call_user_func($func, $this->error, $this->result);
2014-09-22 22:47:48 +02:00
} else {
$this->whens[] = $func;
}
return $this;
}
/**
2015-04-30 19:41:14 +02:00
* Notify the $func callback when resolution progress events are emitted
*
* @param callable $func
* @return self
2014-09-22 22:47:48 +02:00
*/
2015-04-30 19:41:14 +02:00
public function watch(callable $func) {
2014-09-22 22:47:48 +02:00
if (!$this->isResolved) {
$this->watchers[] = $func;
}
return $this;
}
2015-04-30 19:41:14 +02:00
private function resolve(\Exception $error = null, $result = null) {
2014-09-22 22:47:48 +02:00
if ($this->isResolved) {
throw new \LogicException(
2015-04-30 19:41:14 +02:00
"Promise already resolved"
2014-09-22 22:47:48 +02:00
);
} elseif ($result === $this) {
throw new \LogicException(
2015-04-30 19:41:14 +02:00
"A Promise cannot act as its own resolution result"
2014-09-22 22:47:48 +02:00
);
} 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) {
2015-04-30 19:41:14 +02:00
call_user_func($when, $error, $result);
2014-09-22 22:47:48 +02:00
}
$this->whens = $this->watchers = [];
}
}
2015-04-30 19:41:14 +02:00
private function update($progress) {
2014-09-22 22:47:48 +02:00
if ($this->isResolved) {
throw new \LogicException(
2015-04-30 19:41:14 +02:00
"Cannot update resolved promise"
2014-09-22 22:47:48 +02:00
);
}
foreach ($this->watchers as $watcher) {
2015-04-30 19:41:14 +02:00
call_user_func($watcher, $progress);
2014-09-22 22:47:48 +02:00
}
}
}