-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathRecursiveParser.php
191 lines (168 loc) · 4.48 KB
/
RecursiveParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
<?php declare(strict_types=1);
/**
* @package s9e\TextFormatter
* @copyright Copyright (c) The s9e authors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\TextFormatter\Configurator;
use RuntimeException;
use s9e\TextFormatter\Configurator\RecursiveParser\MatcherInterface;
class RecursiveParser
{
/**
* @var array Callback associated with each match name
*/
protected $callbacks = [];
/**
* @var array Match names associated with each group
*/
protected $groupMatches = [];
/**
* @var array Groups associated with each match name
*/
protected $matchGroups = [];
/**
* @var string Regexp used to match input
*/
protected $regexp;
/**
* Parse given string
*
* @param string $str
* @param string $name Allowed match, either match name or group name (default: allow all)
* @return mixed
*/
public function parse(string $str, string $name = '')
{
$regexp = $this->regexp;
if ($name !== '')
{
$restrict = (isset($this->groupMatches[$name])) ? implode('|', $this->groupMatches[$name]) : $name;
$regexp = preg_replace('(\\(\\?<(?!(?:' . $restrict . '|\\w+\\d+)>))', '(*F)$0', $regexp);
}
preg_match($regexp, $str, $m);
if (!isset($m['MARK']))
{
throw new RuntimeException('Cannot parse ' . var_export($str, true));
}
$name = $m['MARK'];
$args = $this->getArguments($m, $name);
return [
'groups' => $this->matchGroups[$name] ?? [],
'match' => $name,
'value' => call_user_func_array($this->callbacks[$name], $args)
];
}
/**
* Set the list of matchers used by this parser
*
* @param MatcherInterface[]
* @return void
*/
public function setMatchers(array $matchers): void
{
$matchRegexps = [];
$this->groupMatches = [];
$this->matchGroups = [];
foreach ($this->getMatchersConfig($matchers) as $matchName => $matchConfig)
{
foreach ($matchConfig['groups'] as $group)
{
$this->groupMatches[$group][] = $matchName;
}
$regexp = $matchConfig['regexp'];
$regexp = str_replace(' ', '\\s*+', $regexp);
$regexp = '(?<' . $matchName . '>' . $regexp . ')(*:' . $matchName . ')';
$matchRegexps[] = $regexp;
$this->callbacks[$matchName] = $matchConfig['callback'];
$this->matchGroups[$matchName] = $matchConfig['groups'];
}
$groupRegexps = [];
foreach ($this->groupMatches as $group => $names)
{
$groupRegexps[] = '(?<' . $group . '>(?&' . implode(')|(?&', $names) . '))';
}
$this->regexp = '((?(DEFINE)' . implode('', $groupRegexps). ')'
. '^(?:' . implode('|', $matchRegexps) . ')$)s';
}
/**
* Get the list of arguments produced by a regexp's match
*
* @param string[] $matches Regexp matches
* @param string $name Regexp name
* @return string[]
*/
protected function getArguments(array $matches, string $name): array
{
$args = [];
$collect = false;
foreach ($matches as $k => $v)
{
if ($k === $name)
{
// Start collecting matches once we reach the target capture
$collect = true;
}
elseif ($collect)
{
if (!is_int($k))
{
// Stop collecting when we reach the next capture
break;
}
$args[] = $v;
}
}
// Remove the first entry, which contains the whole string that was matched
array_shift($args);
return $args;
}
/**
* Collect, normalize, sort and return the config for all matchers
*
* @param MatcherInterface[] $matchers
* @return array
*/
protected function getMatchersConfig(array $matchers): array
{
$matchersConfig = [];
foreach ($matchers as $matcher)
{
foreach ($matcher->getMatchers() as $matchName => $matchConfig)
{
if (is_string($matchConfig))
{
$matchConfig = ['regexp' => $matchConfig];
}
$parts = explode(':', $matchName);
$matchName = array_pop($parts);
$matchConfig += [
'callback' => [$matcher, 'parse' . $matchName],
'groups' => [],
'order' => 0
];
$matchConfig['name'] = $matchName;
$matchConfig['groups'] = array_unique(array_merge($matchConfig['groups'], $parts));
sort($matchConfig['groups']);
$matchersConfig[$matchName] = $matchConfig;
}
}
uasort($matchersConfig, static::class . '::sortMatcherConfig');
return $matchersConfig;
}
/**
* Compare two matchers' config
*
* @param array $a
* @param array $b
* @return integer
*/
protected static function sortMatcherConfig(array $a, array $b): int
{
if ($a['order'] !== $b['order'])
{
return $a['order'] - $b['order'];
}
return strcmp($a['name'], $b['name']);
}
}