CancellationQueue::getSize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Dazzle\Promise\Helper;
4
5
use Dazzle\Promise\PromiseInterface;
6
use Error;
7
use Exception;
8
9
class CancellationQueue
10
{
11
    /**
12
     * @var bool
13
     */
14
    private $started = false;
15
16
    /**
17
     * @var PromiseInterface[]
18
     */
19
    private $queue = [];
20
21
    /**
22
     * @throws Error|Exception
23
     */
24 25
    public function __invoke()
25
    {
26 25
        if ($this->started)
27
        {
28 1
            return null;
29
        }
30
31 25
        $this->started = true;
32 25
        $this->drain();
33
34 24
        return null;
35
    }
36
37
    /**
38
     * @return int
39
     */
40 3
    public function getSize()
41
    {
42 3
        return count($this->queue);
43
    }
44
45
    /**
46
     * @param mixed $cancellable
47
     * @throws Error|Exception
48
     */
49 50
    public function enqueue($cancellable)
50
    {
51 50
        if ($cancellable instanceof PromiseInterface === false)
52
        {
53 15
            return;
54
        }
55
56 42
        $length = array_push($this->queue, $cancellable);
57
58 42
        if ($this->started && 1 === $length)
59
        {
60 9
            $this->drain();
61
        }
62 42
    }
63
64
    /**
65
     * @throws Error|Exception
66
     */
67 25
    private function drain()
68
    {
69 25
        for ($i = key($this->queue); isset($this->queue[$i]); $i++)
70
        {
71 21
            $cancellable = $this->queue[$i];
72 21
            $ex = null;
73
74
            try
75
            {
76 21
                $cancellable->cancel();
77
            }
78 1
            catch (Error $ex)
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
79
            {}
80 1
            catch (Exception $ex)
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
81
            {}
82
83 21
            unset($this->queue[$i]);
84
85 21
            if ($ex)
86
            {
87 1
                throw $ex;
88
            }
89
        }
90
91 24
        $this->queue = [];
92 24
    }
93
}
94