1
0
mirror of https://github.com/danog/amp.git synced 2024-12-15 19:07:22 +01:00
amp/lib/PrivatePromisor.php

75 lines
2.3 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 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 22:47:48 +02:00
*/
trait PrivatePromisor {
private $resolver;
2015-04-30 19:41:14 +02:00
private $updater;
private $promise;
2014-09-22 22:47:48 +02:00
public function __construct() {
// @TODO Replace PrivatePlaceholder with an anonymous class once PHP7 is required
$placeholder = new PrivatePlaceholder;
$resolver = function($error = null, $result = null) {
// bound to private $placeholder::resolve()
$this->resolve($error, $result);
2014-09-22 22:47:48 +02:00
};
2015-04-30 19:41:14 +02:00
$updater = function($progress) {
// bound to private $placeholder::update()
\call_user_func([$this, "update"], $progress);
2015-04-30 19:41:14 +02:00
};
2015-05-19 06:29:03 +02:00
$this->resolver = $resolver->bindTo($placeholder, $placeholder);
$this->updater = $updater->bindTo($placeholder, $placeholder);
$this->promise = $placeholder;
2014-09-22 22:47:48 +02:00
}
/**
* Promise future fulfillment of the returned 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
*
2015-06-01 01:33:55 +02:00
* @param mixed $progress1, $progress2, ... $progressN
2014-09-22 22:47:48 +02:00
* @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 associated promise placeholder as a success
2014-09-22 22:47:48 +02:00
*
* @param mixed $result
* @return void
*/
public function succeed($result = null) {
\call_user_func($this->resolver, $error = null, $result);
2014-09-22 22:47:48 +02:00
}
/**
* Resolve the associated promise placeholder as a failure
2014-09-22 22:47:48 +02:00
*
* The error parameter used to fail a promisor must always be an exception
* instance. However, we cannot typehint this parameter in environments
* where PHP5.x compatibility is required because PHP7 Throwable
* instances will break the typehint.
*
* @param mixed $error An Exception or Throwable in PHP7 environments
2014-09-22 22:47:48 +02:00
* @return void
*/
public function fail($error) {
\call_user_func($this->resolver, $error, $result = null);
2014-09-22 22:47:48 +02:00
}
}