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 PrivateFuture creates a read-only Promise that may *only* be fulfilled by holders of the
|
|
|
|
* actual PrivateFuture instance. This provides an additional layer of API protection over
|
|
|
|
* the standard Future Promisor implementation whose Promise can be resolved by any code
|
|
|
|
* holding a reference to the Future instance.
|
|
|
|
*/
|
|
|
|
class PrivateFuture implements Promisor {
|
|
|
|
private $promise;
|
2015-03-19 16:39:38 +01:00
|
|
|
private $resolver;
|
2014-09-22 22:47:48 +02:00
|
|
|
|
2014-12-02 01:45:57 +01:00
|
|
|
public function __construct() {
|
2015-03-16 20:03:52 +01:00
|
|
|
$this->promise = new Unresolved;
|
2015-03-19 16:39:38 +01:00
|
|
|
$this->resolver = function(bool $isUpdate, ...$args) {
|
|
|
|
if ($isUpdate) {
|
|
|
|
// bound to private Unresolved::update() at call-time
|
|
|
|
$this->update(...$args);
|
|
|
|
} else {
|
|
|
|
// bound to private Unresolved::resolve() at call-time
|
|
|
|
$this->resolve(...$args);
|
|
|
|
}
|
2014-09-22 22:47:48 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Promise future fulfillment via a temporary placeholder value
|
2015-03-19 16:39:57 +01:00
|
|
|
*
|
|
|
|
* @return \Amp\Promise
|
2014-09-22 22:47:48 +02:00
|
|
|
*/
|
2015-03-19 16:14:21 +01:00
|
|
|
public function promise(): Promise {
|
2014-09-22 22:47:48 +02:00
|
|
|
return $this->promise;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2015-03-16 20:03:52 +01:00
|
|
|
* Update subscribers of progress resolving the promised value
|
2014-09-22 22:47:48 +02:00
|
|
|
*
|
|
|
|
* @param mixed $progress
|
|
|
|
* @return void
|
|
|
|
*/
|
2015-03-19 16:26:56 +01:00
|
|
|
public function update(...$progress) {
|
2015-03-19 16:39:38 +01:00
|
|
|
$this->resolver->call($this->promise, $isUpdate = true, ...$progress);
|
2014-09-22 22:47:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Resolve the promised value as a success
|
|
|
|
*
|
|
|
|
* @param mixed $result
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function succeed($result = null) {
|
2015-03-19 16:39:38 +01:00
|
|
|
$this->resolver->call($this->promise, $isUpdate = false, $error = null, $result);
|
2014-09-22 22:47:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Resolve the promised value as a failure
|
|
|
|
*
|
|
|
|
* @param \Exception $error
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function fail(\Exception $error) {
|
2015-03-19 16:39:38 +01:00
|
|
|
$this->resolver->call($this->promise, $isUpdate = false, $error, $result = null);
|
2014-09-22 22:47:48 +02:00
|
|
|
}
|
|
|
|
}
|