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

75 lines
2.5 KiB
PHP
Raw Normal View History

<?php
2016-08-15 23:46:26 -05:00
2016-05-23 22:48:28 -05:00
namespace Amp;
2016-05-21 09:44:52 -05:00
2016-07-12 11:20:06 -05:00
// @codeCoverageIgnoreStart
2016-05-21 09:44:52 -05:00
try {
if (!@\assert(false)) {
development: // PHP 7 development (zend.assertions=1)
/**
* Deferred is a container for a promise that is resolved using the resolve() and fail() methods of this object.
* The contained promise may be accessed using the promise() method. This object should not be part of a public
* API, but used internally to create and resolve a promise.
*/
2016-05-21 09:44:52 -05:00
final class Deferred {
/** @var \Amp\Promise */
2016-11-14 13:59:21 -06:00
private $promise;
2016-05-21 09:44:52 -05:00
/** @var callable */
2016-05-21 09:44:52 -05:00
private $resolve;
/** @var callable */
2016-05-21 09:44:52 -05:00
private $fail;
public function __construct() {
$this->promise = new class($this->resolve, $this->fail) implements Promise {
use CallableMaker, Internal\Placeholder;
public function __construct(&$resolve, &$fail) {
$resolve = $this->callableFromInstanceMethod("resolve");
$fail = $this->callableFromInstanceMethod("fail");
}
};
2016-05-21 09:44:52 -05:00
}
/**
* @return \Amp\Promise
2016-05-21 09:44:52 -05:00
*/
2016-11-14 13:59:21 -06:00
public function promise(): Promise {
return $this->promise;
2016-05-21 09:44:52 -05:00
}
/**
2016-11-14 13:59:21 -06:00
* Fulfill the promise with the given value.
2016-05-21 09:44:52 -05:00
*
* @param mixed $value
*/
public function resolve($value = null) {
2016-08-11 14:35:58 -05:00
($this->resolve)($value);
2016-05-21 09:44:52 -05:00
}
/**
2016-11-14 13:59:21 -06:00
* Fails the promise the the given reason.
2016-05-21 09:44:52 -05:00
*
2016-08-11 14:35:58 -05:00
* @param \Throwable $reason
2016-05-21 09:44:52 -05:00
*/
2016-08-11 14:35:58 -05:00
public function fail(\Throwable $reason) {
($this->fail)($reason);
2016-05-21 09:44:52 -05:00
}
}
} else {
production: // PHP 7 production environment (zend.assertions=0)
/**
* An optimized version of Deferred for production environments that is itself the promise. Eval is used to
* prevent IDEs and other tools from reporting multiple definitions.
*/
2017-04-15 23:16:50 +01:00
eval('namespace Amp;
final class Deferred implements Promise {
use Internal\Placeholder { resolve as public; fail as public; }
public function promise(): Promise { return $this; }
}');
2016-05-21 09:44:52 -05:00
}
} catch (\AssertionError $exception) {
goto development; // zend.assertions=1 and assert.exception=1, use development definition.
2016-07-12 11:20:06 -05:00
} // @codeCoverageIgnoreEnd