1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Version\Comparison\Constraint; |
6
|
|
|
|
7
|
|
|
use ReflectionClass; |
8
|
|
|
use Version\Version; |
9
|
|
|
use Version\Comparison\Exception\InvalidOperationConstraint; |
10
|
|
|
|
11
|
|
|
class OperationConstraint implements Constraint |
12
|
|
|
{ |
13
|
|
|
public const OPERATOR_EQ = '='; |
14
|
|
|
public const OPERATOR_NEQ = '!='; |
15
|
|
|
public const OPERATOR_GT = '>'; |
16
|
|
|
public const OPERATOR_GTE = '>='; |
17
|
|
|
public const OPERATOR_LT = '<'; |
18
|
|
|
public const OPERATOR_LTE = '<='; |
19
|
|
|
|
20
|
|
|
/** @var string */ |
21
|
|
|
protected $operator; |
22
|
|
|
|
23
|
|
|
/** @var Version */ |
24
|
|
|
protected $operand; |
25
|
|
|
|
26
|
17 |
|
public function __construct(string $operator, Version $operand) |
27
|
|
|
{ |
28
|
17 |
|
$this->validateOperator($operator); |
29
|
|
|
|
30
|
16 |
|
$this->operator = $operator; |
31
|
16 |
|
$this->operand = $operand; |
32
|
16 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param string $constraintString |
36
|
|
|
* @return OperationConstraint|CompositeConstraint |
37
|
|
|
*/ |
38
|
13 |
|
public static function fromString(string $constraintString) |
39
|
|
|
{ |
40
|
13 |
|
static $parser = null; |
41
|
|
|
|
42
|
13 |
|
if (null === $parser) { |
43
|
1 |
|
$parser = new OperationConstraintParser(); |
44
|
|
|
} |
45
|
|
|
|
46
|
13 |
|
return $parser->parse($constraintString); |
47
|
|
|
} |
48
|
|
|
|
49
|
5 |
|
public function getOperator(): string |
50
|
|
|
{ |
51
|
5 |
|
return $this->operator; |
52
|
|
|
} |
53
|
|
|
|
54
|
5 |
|
public function getOperand(): Version |
55
|
|
|
{ |
56
|
5 |
|
return $this->operand; |
57
|
|
|
} |
58
|
|
|
|
59
|
12 |
|
public function assert(Version $version): bool |
60
|
|
|
{ |
61
|
12 |
|
switch ($this->operator) { |
62
|
12 |
|
case self::OPERATOR_EQ: |
63
|
2 |
|
return $version->isEqualTo($this->operand); |
64
|
10 |
|
case self::OPERATOR_NEQ: |
65
|
1 |
|
return !$version->isEqualTo($this->operand); |
66
|
9 |
|
case self::OPERATOR_GT: |
67
|
2 |
|
return $version->isGreaterThan($this->operand); |
68
|
7 |
|
case self::OPERATOR_GTE: |
69
|
5 |
|
return $version->isGreaterOrEqualTo($this->operand); |
70
|
3 |
|
case self::OPERATOR_LT: |
71
|
2 |
|
return $version->isLessThan($this->operand); |
72
|
1 |
|
case self::OPERATOR_LTE: |
73
|
1 |
|
return $version->isLessOrEqualTo($this->operand); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
17 |
|
protected function validateOperator($operator): void |
78
|
|
|
{ |
79
|
17 |
|
static $validOperators = null; |
80
|
|
|
|
81
|
17 |
|
if (null === $validOperators) { |
82
|
|
|
$validOperators = (new ReflectionClass($this))->getConstants(); |
83
|
|
|
} |
84
|
|
|
|
85
|
17 |
|
if (! in_array($operator, $validOperators, true)) { |
86
|
1 |
|
throw InvalidOperationConstraint::unsupportedOperator($operator); |
87
|
|
|
} |
88
|
16 |
|
} |
89
|
|
|
} |
90
|
|
|
|