1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Version\Comparison\Constraint; |
6
|
|
|
|
7
|
|
|
use Version\Version; |
8
|
|
|
use Version\Exception\InvalidCompositeConstraintException; |
9
|
|
|
|
10
|
|
|
class CompositeConstraint implements Constraint |
11
|
|
|
{ |
12
|
|
|
public const OPERATOR_AND = 'AND'; |
13
|
|
|
public const OPERATOR_OR = 'OR'; |
14
|
|
|
|
15
|
|
|
/** @var string */ |
16
|
|
|
protected $operator; |
17
|
|
|
|
18
|
|
|
/** @var Constraint[] */ |
19
|
|
|
protected $constraints; |
20
|
|
|
|
21
|
9 |
|
public function __construct(string $operator, Constraint $constraint, Constraint ...$constraints) |
22
|
|
|
{ |
23
|
9 |
|
if (! in_array($operator, [self::OPERATOR_AND, self::OPERATOR_OR], true)) { |
24
|
1 |
|
throw InvalidCompositeConstraintException::forUnsupportedOperator($operator); |
25
|
|
|
} |
26
|
|
|
|
27
|
8 |
|
$this->operator = $operator; |
28
|
8 |
|
$this->constraints = array_merge([$constraint], $constraints); |
29
|
8 |
|
} |
30
|
|
|
|
31
|
5 |
|
public static function and(Constraint $constraint, Constraint ...$constraints): CompositeConstraint |
32
|
|
|
{ |
33
|
5 |
|
return new static(self::OPERATOR_AND, $constraint, ...$constraints); |
34
|
|
|
} |
35
|
|
|
|
36
|
3 |
|
public static function or(Constraint $constraint, Constraint ...$constraints): CompositeConstraint |
37
|
|
|
{ |
38
|
3 |
|
return new static(self::OPERATOR_OR, $constraint, ...$constraints); |
39
|
|
|
} |
40
|
|
|
|
41
|
5 |
|
public function getOperator(): string |
42
|
|
|
{ |
43
|
5 |
|
return $this->operator; |
44
|
|
|
} |
45
|
|
|
|
46
|
3 |
|
public function getConstraints(): array |
47
|
|
|
{ |
48
|
3 |
|
return $this->constraints; |
49
|
|
|
} |
50
|
|
|
|
51
|
2 |
|
public function assert(Version $version): bool |
52
|
|
|
{ |
53
|
2 |
|
if ($this->operator === self::OPERATOR_AND) { |
54
|
1 |
|
return $this->assertAnd($version); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
return $this->assertOr($version); |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
protected function assertAnd(Version $version): bool |
61
|
|
|
{ |
62
|
1 |
|
foreach ($this->constraints as $constraint) { |
63
|
1 |
|
if (! $constraint->assert($version)) { |
64
|
1 |
|
return false; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
return true; |
69
|
|
|
} |
70
|
|
|
|
71
|
1 |
|
protected function assertOr(Version $version): bool |
72
|
|
|
{ |
73
|
1 |
|
foreach ($this->constraints as $constraint) { |
74
|
1 |
|
if ($constraint->assert($version)) { |
75
|
1 |
|
return true; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
return false; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|