Passed
Push — master ( ca9c7f...904700 )
by PHPinnacle
03:16
created

Task::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of PHPinnacle/Ensign.
4
 *
5
 * (c) PHPinnacle Team <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types = 1);
12
13
namespace PHPinnacle\Ensign;
14
15
use Amp\Deferred;
16
use Amp\Loop;
17
use Amp\Promise;
18
19
final class Task implements Promise
20
{
21
    /**
22
     * @var int
23
     */
24
    private $id;
25
26
    /**
27
     * @var Promise
28
     */
29
    private $promise;
30
31
    /**
32
     * @var Token
33
     */
34
    private $token;
35
36
    /**
37
     * @param int     $id
38
     * @param Promise $promise
39
     * @param Token   $token
40
     */
41 12
    public function __construct(int $id, Promise $promise, Token $token)
42
    {
43 12
        $this->id      = $id;
44 12
        $this->promise = $promise;
45 12
        $this->token   = $token;
46 12
    }
47
48
    /**
49
     * @return int
50
     */
51 2
    public function id(): int
52
    {
53 2
        return $this->id;
54
    }
55
56
    /**
57
     * @param string $reason
58
     *
59
     * @return Task
60
     */
61 1
    public function cancel(string $reason = ''): self
62
    {
63 1
        $this->token->cancel($this->id, $reason);
64
65 1
        return $this;
66
    }
67
68
    /**
69
     * @param int $timeout
70
     *
71
     * @return self
72
     */
73 2
    public function timeout(int $timeout): self
74
    {
75 2
        $deferred = new Deferred;
76 2
        $resolved = false;
77
78 2
        $watcher = Loop::delay($timeout, function () use ($deferred, &$resolved) {
79 1
            if ($resolved) {
80
                return;
81
            }
82
83 1
            $resolved = true;
84
85 1
            $deferred->fail(new Exception\TaskTimeout($this->id));
86 2
        });
87
88 2
        $promise = $this->promise;
89 2
        $promise->onResolve(function () use ($deferred, $watcher, &$resolved) {
90 1
            if ($resolved) {
91 1
                return;
92
            }
93
94 1
            $resolved = true;
95
96 1
            Loop::cancel($watcher);
97
98 1
            $deferred->resolve($this->promise);
99 2
        });
100
101 2
        $this->promise = $deferred->promise();
102
103 2
        return $this;
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109 12
    public function onResolve(callable $onResolved)
110
    {
111 12
        $this->token->guard();
112 11
        $this->promise->onResolve($onResolved);
113 11
    }
114
}
115