Passed
Push — master ( 89369f...5a90e9 )
by Vladimir
03:51
created

Deferred::runQueue()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 0
crap 3
1
<?php
2
namespace GraphQL;
3
4
use GraphQL\Executor\Promise\Adapter\SyncPromise;
5
6
class Deferred
7
{
8
    /**
9
     * @var \SplQueue
10
     */
11
    private static $queue;
12
13
    /**
14
     * @var callable
15
     */
16
    private $callback;
17
18
    /**
19
     * @var SyncPromise
20
     */
21
    public $promise;
22
23 218
    public static function getQueue()
24
    {
25 218
        return self::$queue ?: self::$queue = new \SplQueue();
26
    }
27
28 193
    public static function runQueue()
29
    {
30 193
        $q = self::$queue;
31 193
        while ($q && !$q->isEmpty()) {
32
            /** @var self $dfd */
33 39
            $dfd = $q->dequeue();
34 39
            $dfd->run();
35
        }
36 193
    }
37
38 42
    public function __construct(callable $callback)
39
    {
40 42
        $this->callback = $callback;
41 42
        $this->promise = new SyncPromise();
42 42
        self::getQueue()->enqueue($this);
43 42
    }
44
45 1
    public function then($onFulfilled = null, $onRejected = null)
46
    {
47 1
        return $this->promise->then($onFulfilled, $onRejected);
48
    }
49
50 39
    private function run()
51
    {
52
        try {
53 39
            $cb = $this->callback;
54 39
            $this->promise->resolve($cb());
55 18
        } catch (\Exception $e) {
56 18
            $this->promise->reject($e);
57
        } catch (\Throwable $e) {
58
            $this->promise->reject($e);
59
        }
60 39
    }
61
}
62