1
0
mirror of https://github.com/danog/amp.git synced 2024-12-03 09:57:51 +01:00
amp/lib/PrivateFuture.php

67 lines
1.8 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 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;
private $resolver;
2014-09-22 22:47:48 +02:00
public function __construct() {
2015-03-16 20:03:52 +01:00
$this->promise = new Unresolved;
$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
*/
public function update(...$progress) {
$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) {
$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) {
$this->resolver->call($this->promise, $isUpdate = false, $error, $result = null);
2014-09-22 22:47:48 +02:00
}
}