mirror of
https://github.com/danog/amp.git
synced 2024-11-26 20:15:00 +01:00
Add preliminary future combinators
This commit is contained in:
parent
6a613c7356
commit
16c17244e8
17
lib/Aggregate.php
Executable file
17
lib/Aggregate.php
Executable file
@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Alert;
|
||||
|
||||
class Aggregate {
|
||||
|
||||
/**
|
||||
* Create a new Future that will resolve when all Futures in the array resolve
|
||||
*
|
||||
* @param array $futures
|
||||
* @return Future
|
||||
*/
|
||||
public static function all(array $futures) {
|
||||
return (new PromiseGroup($futures))->getFuture();
|
||||
}
|
||||
|
||||
}
|
59
lib/PromiseGroup.php
Executable file
59
lib/PromiseGroup.php
Executable file
@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Alert;
|
||||
|
||||
class PromiseGroup extends Promise {
|
||||
private $futureGroup = [];
|
||||
private $resolvedValues = [];
|
||||
private $isComplete = FALSE;
|
||||
|
||||
public function __construct(array $futureGroup) {
|
||||
if (empty($futureGroup)) {
|
||||
throw new \RuntimeException(
|
||||
sprintf('Array at %s Argument 1 must not be empty', __METHOD__)
|
||||
);
|
||||
}
|
||||
|
||||
parent::__construct();
|
||||
|
||||
$this->futureGroup = $futureGroup;
|
||||
|
||||
foreach ($futureGroup as $key => $future) {
|
||||
if (!$future instanceof Future) {
|
||||
throw new \InvalidArgumentException(
|
||||
sprintf(
|
||||
'Future array required at Argument 1: %s provided at index %s',
|
||||
gettype($future),
|
||||
$key
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$isComplete = $future->isComplete();
|
||||
|
||||
if ($isComplete && $this->resolveIndividualFuture($future, $key)) {
|
||||
return;
|
||||
} elseif (!$isComplete) {
|
||||
$future->onComplete(function($future) use ($key) {
|
||||
$this->resolveIndividualFuture($future, $key);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function resolveIndividualFuture($future, $key) {
|
||||
unset($this->futureGroup[$key]);
|
||||
|
||||
if ($this->isComplete) {
|
||||
return TRUE;
|
||||
} elseif ($future->succeeded()) {
|
||||
$this->resolvedValues[$key] = $future->getValue();
|
||||
return ($this->isComplete = empty($this->futureGroup))
|
||||
? parent::succeed($this->resolvedValues)
|
||||
: FALSE;
|
||||
} else {
|
||||
parent::fail($future->getError());
|
||||
return ($this->isComplete = TRUE);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user