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