1 | <?php |
||
10 | class Parser |
||
11 | { |
||
12 | /** |
||
13 | * @var string[] |
||
14 | */ |
||
15 | private $tokens; |
||
16 | |||
17 | /** |
||
18 | * @var string[] |
||
19 | */ |
||
20 | private $span; |
||
21 | |||
22 | /** |
||
23 | * @var int |
||
24 | */ |
||
25 | private $lineNumber = 0; |
||
26 | |||
27 | /** |
||
28 | * @var bool |
||
29 | */ |
||
30 | private $strict; |
||
31 | |||
32 | 2 | public function __construct(string $changelog, bool $strict = true) |
|
33 | { |
||
34 | 2 | $this->tokens = preg_split("/\n/", $changelog); |
|
35 | 2 | $this->strict = $strict; |
|
36 | 2 | } |
|
37 | |||
38 | 2 | private function current(): string |
|
39 | { |
||
40 | 2 | if (count($this->tokens) === 0) { |
|
41 | 1 | return ""; |
|
42 | } |
||
43 | 2 | return $this->tokens[0]; |
|
44 | } |
||
45 | |||
46 | 2 | private function next(): string |
|
47 | { |
||
48 | 2 | if (count($this->tokens) === 0) { |
|
49 | throw $this->error('Unexpected end of file'); |
||
50 | } |
||
51 | |||
52 | 2 | $n = ++$this->lineNumber; |
|
53 | 2 | $line = array_shift($this->tokens); |
|
54 | |||
55 | 2 | $this->span[] = " {$n}: $line"; |
|
56 | |||
57 | 2 | if (count($this->span) > 4) { |
|
58 | 2 | array_shift($this->span); |
|
59 | } |
||
60 | |||
61 | 2 | return $line; |
|
62 | } |
||
63 | |||
64 | 2 | private function acceptEmptyLine() |
|
65 | { |
||
66 | 2 | if ($this->strict) { |
|
67 | 1 | if ("" !== $this->next()) { |
|
68 | 1 | throw $this->error("Expected an empty line"); |
|
69 | } |
||
70 | } else { |
||
71 | 1 | while (preg_match('/^\s*$/', $this->current()) && count($this->tokens) > 0) { |
|
72 | 1 | $this->next(); |
|
73 | } |
||
74 | } |
||
75 | 2 | } |
|
76 | |||
77 | 2 | private function acceptEof() |
|
78 | { |
||
79 | 2 | if (count($this->tokens) !== 0) { |
|
80 | $this->next(); |
||
81 | throw $this->error("Expected EOF"); |
||
82 | } |
||
83 | 2 | } |
|
84 | |||
85 | 2 | private function matchVersion($line, &$m = null) |
|
86 | { |
||
87 | 2 | return preg_match('/^\#\# \s ( v\d+\.\d+\.\d+(-[\d\w\.]+)? | master )$/x', $line, $m); |
|
88 | } |
||
89 | |||
90 | private function error($message): ParseException |
||
101 | |||
102 | 2 | public function parse(): Changelog |
|
103 | { |
||
104 | 2 | $changelog = $this->parseTitle(); |
|
105 | |||
106 | 2 | $this->acceptEmptyLine(); |
|
107 | 2 | $this->acceptEmptyLine(); |
|
122 | |||
123 | 2 | private function parseTitle(): Changelog |
|
133 | |||
134 | 2 | private function parseVersion(): Version |
|
184 | |||
185 | 2 | private function parseItems() |
|
206 | |||
207 | 2 | private function parseReferences() |
|
219 | } |
||
220 |