Total Complexity | 7 |
Total Lines | 94 |
Duplicated Lines | 0 % |
Coverage | 90.63% |
Changes | 0 |
1 | <?php |
||
20 | final class Task implements Promise |
||
21 | { |
||
22 | /** |
||
23 | * @var UUID |
||
24 | */ |
||
25 | private $id; |
||
26 | |||
27 | /** |
||
28 | * @var Promise |
||
29 | */ |
||
30 | private $promise; |
||
31 | |||
32 | /** |
||
33 | * @var Token |
||
34 | */ |
||
35 | private $token; |
||
36 | |||
37 | /** |
||
38 | * @param UUID $id |
||
39 | * @param Promise $promise |
||
40 | * @param Token $token |
||
41 | */ |
||
42 | 11 | public function __construct(UUID $id, Promise $promise, Token $token) |
|
43 | { |
||
44 | 11 | $this->id = $id; |
|
45 | 11 | $this->promise = $promise; |
|
46 | 11 | $this->token = $token; |
|
47 | 11 | } |
|
48 | |||
49 | /** |
||
50 | * @return UUID |
||
51 | */ |
||
52 | public function id(): UUID |
||
53 | { |
||
54 | return $this->id; |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * @param string $reason |
||
59 | * |
||
60 | * @return Task |
||
61 | */ |
||
62 | 1 | public function cancel(string $reason = null): self |
|
63 | { |
||
64 | 1 | $this->token->cancel($reason); |
|
65 | |||
66 | 1 | return $this; |
|
67 | } |
||
68 | |||
69 | /** |
||
70 | * @param int $timeout |
||
71 | * |
||
72 | * @return self |
||
73 | */ |
||
74 | 2 | public function timeout(int $timeout): self |
|
75 | { |
||
76 | 2 | $deferred = new Deferred; |
|
77 | 2 | $resolved = false; |
|
78 | |||
79 | 2 | $watcher = Loop::delay($timeout, function () use ($deferred, &$resolved) { |
|
80 | 1 | if ($resolved) { |
|
81 | return; |
||
82 | } |
||
83 | |||
84 | 1 | $resolved = true; |
|
85 | |||
86 | 1 | $deferred->fail(new Exception\TaskTimeout((string) $this->id)); |
|
87 | 2 | }); |
|
88 | |||
89 | 2 | $promise = $this->promise; |
|
90 | 2 | $promise->onResolve(function () use ($deferred, $watcher, &$resolved) { |
|
91 | 1 | if ($resolved) { |
|
92 | 1 | return; |
|
93 | } |
||
94 | |||
95 | 1 | $resolved = true; |
|
96 | |||
97 | 1 | Loop::cancel($watcher); |
|
98 | |||
99 | 1 | $deferred->resolve($this->promise); |
|
100 | 2 | }); |
|
101 | |||
102 | 2 | $this->promise = $deferred->promise(); |
|
103 | |||
104 | 2 | return $this; |
|
105 | } |
||
106 | |||
107 | /** |
||
108 | * {@inheritdoc} |
||
109 | */ |
||
110 | 11 | public function onResolve(callable $onResolved) |
|
114 | 10 | } |
|
115 | } |
||
116 |