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

111 lines
2.9 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 $isWaiting = false;
private $isResolved = false;
private $watchers = [];
private $whens = [];
private $error;
private $result;
/**
* Notify the $func callback when the promise resolves (whether successful or not)
*
* @param callable $func
* @return self
*/
public function when(callable $func) {
if ($this->isResolved) {
$func($this->error, $this->result);
} else {
$this->whens[] = $func;
}
return $this;
}
/**
* Notify the $func callback when resolution progress events are emitted
*
* @param callable $func
* @return self
*/
public function watch(callable $func) {
if (!$this->isResolved) {
$this->watchers[] = $func;
}
return $this;
}
/**
* This method is deprecated. New code should use Amp\wait($promise) instead.
2014-09-22 22:47:48 +02:00
*/
public function wait() {
trigger_error(
'Amp\\Promise::wait() is deprecated and scheduled for removal. ' .
'Please update code to use Amp\\wait($promise) instead.',
E_USER_DEPRECATED
);
2014-09-22 22:47:48 +02:00
$isWaiting = true;
$resolvedError = $resolvedResult = null;
$this->when(function($error, $result) use (&$isWaiting, &$resolvedError, &$resolvedResult) {
$isWaiting = false;
2014-09-22 22:47:48 +02:00
$resolvedError = $error;
$resolvedResult = $result;
});
$reactor = getReactor();
while ($isWaiting) {
$reactor->tick();
2014-09-22 22:47:48 +02:00
}
if ($resolvedError) {
throw $resolvedError;
}
return $resolvedResult;
}
private function resolve(\Exception $error = null, $result = null) {
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 = [];
}
}
private function update($progress) {
if ($this->isResolved) {
throw new \LogicException(
'Cannot update resolved promise'
);
}
foreach ($this->watchers as $watcher) {
$watcher($progress);
}
}
}