Completed
Push — master ( 37e0f8...cfb38a )
by Randy
02:34
created

EnforcementTrait   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 93
rs 10
c 0
b 0
f 0
wmc 15
lcom 1
cbo 1

7 Methods

Rating   Name   Duplication   Size   Complexity  
A orThrow() 0 8 2
A verify() 0 10 2
A enforce() 0 11 3
A approveEnforcementWith() 0 10 3
A approveEnforcement() 0 6 2
A isEnforcementFulfilled() 0 4 2
A hasEnforcement() 0 4 1
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
}