1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Thruster\Component\Promise; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class FulfilledPromise |
7
|
|
|
* |
8
|
|
|
* @package Thruster\Component\Promise |
9
|
|
|
* @author Aurimas Niekis <[email protected]> |
10
|
|
|
*/ |
11
|
|
|
class FulfilledPromise implements ExtendedPromiseInterface, CancellablePromiseInterface |
12
|
|
|
{ |
13
|
|
|
private $value; |
14
|
|
|
|
15
|
339 |
|
public function __construct($value = null) |
16
|
|
|
{ |
17
|
339 |
|
if ($value instanceof PromiseInterface) { |
18
|
1 |
|
throw new \InvalidArgumentException( |
19
|
|
|
'You cannot create Thruster\Component\Promise\FulfilledPromise with a promise.' . |
20
|
1 |
|
' Use Thruster\Component\Promise\resolve($promiseOrValue) instead.' |
21
|
|
|
); |
22
|
|
|
} |
23
|
|
|
|
24
|
339 |
|
$this->value = $value; |
25
|
339 |
|
} |
26
|
|
|
|
27
|
213 |
View Code Duplication |
public function then( |
|
|
|
|
28
|
|
|
callable $onFulfilled = null, |
29
|
|
|
callable $onRejected = null, |
30
|
|
|
callable $onProgress = null |
31
|
|
|
) : PromiseInterface { |
32
|
213 |
|
if (null === $onFulfilled) { |
33
|
26 |
|
return $this; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
try { |
37
|
194 |
|
return resolve($onFulfilled($this->value)); |
38
|
18 |
|
} catch (\Exception $exception) { |
39
|
18 |
|
return new RejectedPromise($exception); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
136 |
|
public function done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) |
44
|
|
|
{ |
45
|
136 |
|
if (null === $onFulfilled) { |
46
|
8 |
|
return; |
47
|
|
|
} |
48
|
|
|
|
49
|
128 |
|
$result = $onFulfilled($this->value); |
50
|
|
|
|
51
|
121 |
|
if ($result instanceof ExtendedPromiseInterface) { |
52
|
7 |
|
$result->done(); |
53
|
|
|
} |
54
|
114 |
|
} |
55
|
|
|
|
56
|
1 |
|
public function otherwise(callable $onRejected) : ExtendedPromiseInterface |
57
|
|
|
{ |
58
|
1 |
|
return $this; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function always(callable $onFulfilledOrRejected) : ExtendedPromiseInterface |
62
|
|
|
{ |
63
|
|
|
return $this->then(function ($value) use ($onFulfilledOrRejected) { |
64
|
5 |
|
return resolve($onFulfilledOrRejected())->then(function () use ($value) { |
65
|
4 |
|
return $value; |
66
|
5 |
|
}); |
67
|
6 |
|
}); |
68
|
|
|
} |
69
|
|
|
|
70
|
1 |
|
public function progress(callable $onProgress) : ExtendedPromiseInterface |
71
|
|
|
{ |
72
|
1 |
|
return $this; |
73
|
|
|
} |
74
|
|
|
|
75
|
4 |
|
public function cancel() |
76
|
|
|
{ |
77
|
4 |
|
} |
78
|
|
|
} |
79
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.