appwrite/src/Appwrite/GraphQL/CoroutinePromiseAdapter.php

98 lines
3 KiB
PHP
Raw Normal View History

2022-04-05 13:48:51 +00:00
<?php
namespace Appwrite\GraphQL;
use GraphQL\Error\InvariantViolation;
use GraphQL\Executor\Promise\Promise;
use GraphQL\Executor\Promise\PromiseAdapter;
use GraphQL\Utils\Utils;
2022-04-08 07:04:15 +00:00
class CoroutinePromiseAdapter implements PromiseAdapter
2022-04-05 13:48:51 +00:00
{
public function isThenable($value): bool
{
return $value instanceof Promise;
2022-04-05 13:48:51 +00:00
}
public function convertThenable($thenable): Promise
{
if (!$thenable instanceof Promise) {
2022-04-05 13:48:51 +00:00
throw new InvariantViolation('Expected instance of SwoolePromise, got ' . Utils::printSafe($thenable));
}
return new Promise($thenable, $this);
}
public function then(Promise $promise, ?callable $onFulfilled = null, ?callable $onRejected = null): Promise
{
2022-04-08 07:04:15 +00:00
/** @var CoroutinePromise $adoptedPromise */
2022-04-05 13:48:51 +00:00
$adoptedPromise = $promise->adoptedPromise;
return new Promise($adoptedPromise->then($onFulfilled, $onRejected), $this);
}
public function create(callable $resolver): Promise
{
2022-04-08 07:04:15 +00:00
$promise = new CoroutinePromise();
2022-04-05 13:48:51 +00:00
try {
$resolver(
[$promise, 'resolve'],
[$promise, 'reject'],
);
} catch (\Throwable $e) {
$promise->reject($e);
}
return new Promise($promise, $this);
}
public function createFulfilled($value = null): Promise
{
2022-04-08 07:04:15 +00:00
$promise = new CoroutinePromise();
2022-04-05 13:48:51 +00:00
return new Promise($promise->resolve($value), $this);
}
public function createRejected($reason): Promise
{
2022-04-08 07:04:15 +00:00
$promise = new CoroutinePromise();
2022-04-05 13:48:51 +00:00
return new Promise($promise->reject($reason), $this);
}
public function all(array $promisesOrValues): Promise
{
2022-04-08 07:04:15 +00:00
$all = new CoroutinePromise();
2022-04-05 13:48:51 +00:00
$total = count($promisesOrValues);
$count = 0;
$result = [];
2022-04-07 06:41:53 +00:00
\Co\run(function ($promisesOrValues, $all, $total, &$count, $result) {
foreach ($promisesOrValues as $index => $promiseOrValue) {
go(function ($index, $promiseOrValue, $all, $total, &$count, $result) {
2022-04-08 07:04:15 +00:00
if (!($promiseOrValue instanceof CoroutinePromise)) {
$result[$index] = $promiseOrValue;
2022-04-05 13:48:51 +00:00
$count++;
return;
}
$result[$index] = null;
$promiseOrValue->then(
static function ($value) use ($index, &$count, $total, &$result, $all): void {
$result[$index] = $value;
$count++;
2022-04-07 06:41:53 +00:00
if ($count === $total) {
$all->resolve($result);
}
},
[$all, 'reject']
);
}, $index, $promiseOrValue, $all, $total, $count, $result);
2022-04-05 13:48:51 +00:00
}
}, $promisesOrValues, $all, $total, $count, $result);
2022-04-05 13:48:51 +00:00
if ($count === $total) {
$all->resolve($result);
}
return new Promise($all, $this);
}
}