|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Dgame\Ensurance; |
|
4
|
|
|
|
|
5
|
|
|
use Prophecy\Exception\Exception; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class EnforcementTrait |
|
9
|
|
|
* @package Dgame\Ensurance |
|
10
|
|
|
*/ |
|
11
|
|
|
trait EnforcementTrait |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @var Enforcement|null |
|
15
|
|
|
*/ |
|
16
|
|
|
private $enforcement; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @param string|Exception $exception |
|
20
|
|
|
* @param array ...$args |
|
21
|
|
|
* |
|
22
|
|
|
* @return $this |
|
23
|
|
|
*/ |
|
24
|
|
|
final public function orThrow($exception, ...$args) |
|
25
|
|
|
{ |
|
26
|
|
|
if ($this->hasEnforcement()) { |
|
27
|
|
|
$this->enforcement->orThrow($exception, ...$args); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
return $this; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @return bool |
|
35
|
|
|
*/ |
|
36
|
|
|
final public function verify(): bool |
|
37
|
|
|
{ |
|
38
|
|
|
if (!$this->isEnforcementFulfilled()) { |
|
39
|
|
|
$this->approveEnforcement(); |
|
40
|
|
|
|
|
41
|
|
|
return false; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
return true; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* @param bool $condition |
|
49
|
|
|
* |
|
50
|
|
|
* @return $this |
|
51
|
|
|
*/ |
|
52
|
|
|
final protected function enforce(bool $condition) |
|
53
|
|
|
{ |
|
54
|
|
|
$enforcement = new Enforcement($condition); |
|
55
|
|
|
if (!$this->isEnforcementFulfilled() && !$enforcement->isFulfilled()) { |
|
56
|
|
|
$this->approveEnforcementWith($enforcement); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
$this->enforcement = $enforcement; |
|
60
|
|
|
|
|
61
|
|
|
return $this; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @param Enforcement $enforcement |
|
66
|
|
|
*/ |
|
67
|
|
|
private function approveEnforcementWith(Enforcement $enforcement) |
|
68
|
|
|
{ |
|
69
|
|
|
if ($this->hasEnforcement()) { |
|
70
|
|
|
if ($this->enforcement->hasException()) { |
|
71
|
|
|
$enforcement->setException($this->enforcement->getException()); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
$this->enforcement->approve(); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
/** |
|
79
|
|
|
* |
|
80
|
|
|
*/ |
|
81
|
|
|
private function approveEnforcement() |
|
82
|
|
|
{ |
|
83
|
|
|
if ($this->hasEnforcement()) { |
|
84
|
|
|
$this->enforcement->approve(); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
|
|
/** |
|
89
|
|
|
* @return bool |
|
90
|
|
|
*/ |
|
91
|
|
|
final protected function isEnforcementFulfilled(): bool |
|
92
|
|
|
{ |
|
93
|
|
|
return $this->hasEnforcement() && $this->enforcement->isFulfilled(); |
|
94
|
|
|
} |
|
95
|
|
|
|
|
96
|
|
|
/** |
|
97
|
|
|
* @return bool |
|
98
|
|
|
*/ |
|
99
|
|
|
private function hasEnforcement(): bool |
|
100
|
|
|
{ |
|
101
|
|
|
return $this->enforcement !== null; |
|
102
|
|
|
} |
|
103
|
|
|
} |