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 {
|
2015-03-19 16:39:38 +01:00
|
|
|
private $resolver;
|
2015-04-30 19:41:14 +02:00
|
|
|
private $updater;
|
|
|
|
private $promise;
|
2014-09-22 22:47:48 +02:00
|
|
|
|
2014-12-02 01:45:57 +01:00
|
|
|
public function __construct() {
|
2015-04-30 19:41:14 +02:00
|
|
|
$unresolved = new Unresolved;
|
|
|
|
$resolver = function(\Exception $error = null, $result = null) {
|
|
|
|
$this->resolve($error, $result); // bound to private Unresolved::resolve()
|
2014-09-22 22:47:48 +02:00
|
|
|
};
|
2015-04-30 19:41:14 +02:00
|
|
|
$updater = function($progress) {
|
|
|
|
$this->update($progress); // bound to private Unresolved::update()
|
|
|
|
};
|
|
|
|
$this->resolver = $resolver->bindTo($unresolved, $unresolved);
|
|
|
|
$this->updater = $updater->bindTo($unresolved, $unresolved);
|
|
|
|
$this->promise = $unresolved;
|
2014-09-22 22:47:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Promise future fulfillment via a temporary placeholder value
|
2015-04-30 19:41:14 +02:00
|
|
|
*
|
2015-03-19 16:39:57 +01:00
|
|
|
* @return \Amp\Promise
|
2014-09-22 22:47:48 +02:00
|
|
|
*/
|
2015-04-30 19:41:14 +02:00
|
|
|
public function promise() {
|
2014-09-22 22:47:48 +02:00
|
|
|
return $this->promise;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2015-04-30 19:41:14 +02:00
|
|
|
* Update watchers of progress resolving the promised value
|
2014-09-22 22:47:48 +02:00
|
|
|
*
|
|
|
|
* @param mixed $progress
|
|
|
|
* @return void
|
|
|
|
*/
|
2015-04-30 19:41:14 +02:00
|
|
|
public function update($progress) {
|
|
|
|
call_user_func($this->updater, $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-04-30 19:41:14 +02:00
|
|
|
call_user_func($this->resolver, $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-04-30 19:41:14 +02:00
|
|
|
call_user_func($this->resolver, $error, $result = null);
|
2014-09-22 22:47:48 +02:00
|
|
|
}
|
2015-04-30 19:41:14 +02:00
|
|
|
}
|