Passed
Push — master ( 2d6ed9...31b4e9 )
by PHPinnacle
05:04
created

Task::onResolve()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
nc 1
nop 1
dl 0
loc 4
c 0
b 0
f 0
cc 1
ccs 3
cts 3
cp 1
crap 1
rs 10
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 9
    public function __construct(int $id, Promise $promise, Token $token)
42
    {
43 9
        $this->id      = $id;
44 9
        $this->promise = $promise;
45 9
        $this->token   = $token;
46 9
    }
47
48
    /**
49
     * @return int
50
     */
51
    public function id(): int
52
    {
53
        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
    public function timeout(int $timeout): self
74
    {
75
        $deferred = new Deferred;
76
77
        $watcher = Loop::delay($timeout, function () use ($deferred) {
78
            $deferred->fail(new Exception\TaskTimeout($this->id));
79
        });
80
        Loop::unreference($watcher);
81
82
        $promise = $this->promise;
83
        $promise->onResolve(function () use ($deferred, $watcher) {
84
            Loop::cancel($watcher);
85
86
            $deferred->resolve($this->promise);
87
        });
88
89
        $this->promise = $deferred->promise();
90
91
        return $this;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 9
    public function onResolve(callable $onResolved)
98
    {
99 9
        $this->token->guard();
100 8
        $this->promise->onResolve($onResolved);
101 8
    }
102
}
103