This repository has been archived by the owner on Feb 16, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TriggerManager.php
109 lines (91 loc) · 2.96 KB
/
TriggerManager.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace Innmind\ProvisionerBundle;
use Innmind\ProvisionerBundle\Voter\VoterInterface;
use Symfony\Component\Console\Input\InputInterface;
class TriggerManager
{
const STRATEGY_AFFIRMATIVE = 'affirmative';
const STRATEGY_CONSENSUS = 'consensus';
const STRATEGY_UNANIMOUS = 'unanimous';
protected $voters = [];
protected $strategy;
protected $allowIfEqualGrantedDeniedDecisions;
protected $allowIfAllAbstainDecisions;
public function __construct($strategy = self::STRATEGY_AFFIRMATIVE, $allowIfEqualGrantedDeniedDecisions = true, $allowIfAllAbstainDecisions = false)
{
if (!defined(sprintf('self::STRATEGY_%s', strtoupper($strategy)))) {
throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported', $strategy));
}
$this->strategy = $strategy;
$this->allowIfEqualGrantedDeniedDecisions = $allowIfEqualGrantedDeniedDecisions;
$this->allowIfAllAbstainDecisions = $allowIfAllAbstainDecisions;
}
/**
* Add a new voter to the trigger manager
*
* @param VoterInterface $voter
*
* @return TriggerManager self
*/
public function addVoter(VoterInterface $voter)
{
$this->voters[] = $voter;
return $this;
}
/**
* Decide if the decision manager should be triggered or not
*
* @param string $command
* @param InputInterface $input
*
* @return bool
*/
public function decide($command, InputInterface $input)
{
$grant = 0;
$deny = 0;
$abstain = 0;
foreach ($this->voters as $voter) {
if (!$voter->supportsCommand($command)) {
continue;
}
$vote = $voter->vote($command, $input);
switch ($vote) {
case VoterInterface::TRIGGER_GRANTED:
$grant++;
break;
case VoterInterface::TRIGGER_DENIED:
$deny++;
break;
default:
$abstain++;
break;
}
}
switch ($this->strategy) {
case self::STRATEGY_AFFIRMATIVE:
return $grant > 0;
case self::STRATEGY_CONSENSUS:
if ($grant > $deny) {
return true;
}
if ($deny > $grant) {
return false;
}
if ($grant === $deny && $grant !== 0) {
return $this->allowIfEqualGrantedDeniedDecisions;
}
return $this->allowIfAllAbstainDecisions;
case self::STRATEGY_UNANIMOUS:
if ($deny > 0) {
return false;
}
if ($grant > 0) {
return true;
}
return $this->allowIfAllAbstainDecisions;
default:
return false;
}
}
}