Passed
Pull Request — 2.x.x (#24)
by Koldo
17:38 queued 13:31
created

ResolveGenerator::toResponse()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 15
c 1
b 0
f 1
dl 0
loc 23
ccs 0
cts 15
cp 0
rs 9.4555
cc 5
nc 2
nop 1
crap 30
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\React;
6
7
use Generator;
8
use Psr\Http\Message\ResponseInterface;
9
use React\Promise\Promise;
10
use React\Promise\PromiseInterface;
11
use Throwable;
12
13
final class ResolveGenerator
14
{
15
    /**
16
     * @param callable<Generator>|ResponseInterface|PromiseInterface $generator
17
     */
18
    public static function toResponse(
19
        callable|ResponseInterface|PromiseInterface $callback
20
    ): PromiseInterface|ResponseInterface {
21
        if (false === is_callable($callback)) {
22
            return $callback;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $callback could return the type callable which is incompatible with the type-hinted return Psr\Http\Message\Respons...romise\PromiseInterface. Consider adding an additional type-check to rule them out.
Loading history...
23
        }
24
25
        return new Promise(
26
            static function (callable $resolve, callable $reject) use ($callback): void {
27
                try {
28
                    /** @var Generator<PromiseInterface|ResponseInterface> $generator */
29
                    $generator = $callback();
30
                    while ($generator->valid()) {
31
                        $item = $generator->current();
32
                        if ($item instanceof PromiseInterface) {
33
                            $item->then(static fn($solved) => $generator->send($solved));
34
                            continue;
35
                        }
36
                        $generator->send($item);
37
                    }
38
                    $resolve($generator->getReturn());
39
                } catch (Throwable $exception) {
40
                    $reject($exception);
41
                }
42
            }
43
        );
44
    }
45
}
46