1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Version\Constraint\Parser; |
6
|
|
|
|
7
|
|
|
use Version\Constraint\ConstraintInterface; |
8
|
|
|
use Version\Constraint\Constraint; |
9
|
|
|
use Version\Version; |
10
|
|
|
use Version\Exception\InvalidConstraintStringException; |
11
|
|
|
use Version\Exception\ExceptionInterface; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @author Nikola Posa <[email protected]> |
15
|
|
|
*/ |
16
|
|
|
abstract class AbstractParser implements ParserInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var string |
20
|
|
|
*/ |
21
|
|
|
protected $constraintString; |
22
|
|
|
|
23
|
12 |
|
public function parse(string $constraintString) : ConstraintInterface |
24
|
|
|
{ |
25
|
12 |
|
$constraintString = trim($constraintString); |
26
|
|
|
|
27
|
12 |
|
if ('' === $constraintString) { |
28
|
1 |
|
throw InvalidConstraintStringException::forEmptyConstraintString(); |
29
|
|
|
} |
30
|
|
|
|
31
|
11 |
|
$this->constraintString = $constraintString; |
32
|
|
|
|
33
|
11 |
|
return $this->doParse(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
abstract protected function doParse() : ConstraintInterface; |
37
|
|
|
|
38
|
4 |
|
protected function error() : void |
39
|
|
|
{ |
40
|
4 |
|
throw InvalidConstraintStringException::forConstraintString($this->constraintString); |
41
|
|
|
} |
42
|
|
|
|
43
|
11 |
|
protected function buildConstraintFromStringUnit(string $constraintStringUnit) : ConstraintInterface |
44
|
|
|
{ |
45
|
11 |
|
[$operator, $operandString] = array_values($this->parseConstraintStringUnit($constraintStringUnit)); |
|
|
|
|
46
|
|
|
|
47
|
11 |
|
if (empty($operandString)) { |
48
|
1 |
|
$this->error(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
try { |
52
|
10 |
|
return Constraint::fromProperties( |
53
|
10 |
|
$operator ?: Constraint::OPERATOR_EQ, |
54
|
10 |
|
Version::fromString($operandString) |
55
|
|
|
); |
56
|
2 |
|
} catch (ExceptionInterface $ex) { |
57
|
2 |
|
$this->error(); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
11 |
|
protected function parseConstraintStringUnit(string $constraintStringUnit) : array |
62
|
|
|
{ |
63
|
11 |
|
$i = 0; |
64
|
11 |
|
while (isset($constraintStringUnit[$i]) && !ctype_digit($constraintStringUnit[$i])) { |
65
|
10 |
|
$i++; |
66
|
|
|
} |
67
|
|
|
|
68
|
11 |
|
$operator = substr($constraintStringUnit, 0, $i); |
69
|
11 |
|
$operand = substr($constraintStringUnit, $i); |
70
|
|
|
|
71
|
|
|
return [ |
72
|
11 |
|
'operator' => $operator, |
73
|
11 |
|
'operand' => $operand, |
74
|
|
|
]; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.