1
0
mirror of https://github.com/danog/amp.git synced 2025-01-22 21:31:18 +01:00
amp/lib/PrivatePromisor.php

69 lines
1.8 KiB
PHP
Raw Normal View History

2014-09-22 16:47:48 -04:00
<?php
2014-09-22 22:38:32 -04:00
namespace Amp;
2014-09-22 16:47:48 -04:00
/**
* A PrivatePromisor creates read-only Promise instances that can only be
* resolved by holders of the PrivatePromisor instance. This creates an
* additional layer of API protection beyond the PublicPromisor.
2014-09-22 16:47:48 -04:00
*/
trait PrivatePromisor {
private $resolver;
2015-04-30 13:41:14 -04:00
private $updater;
private $promise;
2014-09-22 16:47:48 -04:00
public function __construct() {
$placeholder = new PrivatePlaceholder;
2015-04-30 13:41:14 -04:00
$resolver = function(\Exception $error = null, $result = null) {
// bound to private PrivatePlaceholder::resolve()
$this->resolve($error, $result);
2014-09-22 16:47:48 -04:00
};
2015-04-30 13:41:14 -04:00
$updater = function($progress) {
// bound to private PrivatePlaceholder::update()
$this->update($progress);
2015-04-30 13:41:14 -04:00
};
2015-05-19 00:29:03 -04:00
$this->resolver = $resolver->bindTo($placeholder, $placeholder);
$this->updater = $updater->bindTo($placeholder, $placeholder);
$this->promise = $placeholder;
2014-09-22 16:47:48 -04:00
}
/**
* Promise future fulfillment of the returned placeholder value
2015-04-30 13:41:14 -04:00
*
2015-03-19 11:39:57 -04:00
* @return \Amp\Promise
2014-09-22 16:47:48 -04:00
*/
2015-04-30 13:41:14 -04:00
public function promise() {
2014-09-22 16:47:48 -04:00
return $this->promise;
}
/**
2015-04-30 13:41:14 -04:00
* Update watchers of progress resolving the promised value
2014-09-22 16:47:48 -04:00
*
* @param mixed $progress
* @return void
*/
2015-04-30 13:41:14 -04:00
public function update($progress) {
call_user_func($this->updater, $progress);
2014-09-22 16:47:48 -04:00
}
/**
* Resolve the associated promise placeholder as a success
2014-09-22 16:47:48 -04:00
*
* @param mixed $result
* @return void
*/
public function succeed($result = null) {
2015-04-30 13:41:14 -04:00
call_user_func($this->resolver, $error = null, $result);
2014-09-22 16:47:48 -04:00
}
/**
* Resolve the associated promise placeholder as a failure
2014-09-22 16:47:48 -04:00
*
* @param \Exception $error
* @return void
*/
public function fail(\Exception $error) {
2015-04-30 13:41:14 -04:00
call_user_func($this->resolver, $error, $result = null);
2014-09-22 16:47:48 -04:00
}
}