MediaWiki master
MagicWordArray.php
Go to the documentation of this file.
1<?php
21namespace MediaWiki\Parser;
22
23use LogicException;
26
36
38 public $names = [];
39 private MagicWordFactory $factory;
40
42 private $hash;
43
45 private $baseRegex;
46
48 private $regex;
49
54 public function __construct( $names = [], MagicWordFactory $factory = null ) {
55 $this->names = $names;
56 $this->factory = $factory ?: MediaWikiServices::getInstance()->getMagicWordFactory();
57 }
58
64 public function add( $name ): void {
65 $this->names[] = $name;
66 $this->hash = $this->baseRegex = $this->regex = null;
67 }
68
74 public function getHash(): array {
75 if ( $this->hash === null ) {
76 $this->hash = [ 0 => [], 1 => [] ];
77 foreach ( $this->names as $name ) {
78 $magic = $this->factory->get( $name );
79 $case = intval( $magic->isCaseSensitive() );
80 foreach ( $magic->getSynonyms() as $syn ) {
81 if ( !$case ) {
82 $syn = $this->factory->getContentLanguage()->lc( $syn );
83 }
84 $this->hash[$case][$syn] = $name;
85 }
86 }
87 }
88 return $this->hash;
89 }
90
102 public function getBaseRegex( bool $capture = true, string $delimiter = '/' ): array {
103 if ( $capture && $delimiter === '/' && $this->baseRegex !== null ) {
104 return $this->baseRegex;
105 }
106 $regex = [ 0 => [], 1 => [] ];
107 foreach ( $this->names as $name ) {
108 $magic = $this->factory->get( $name );
109 $case = $magic->isCaseSensitive() ? 1 : 0;
110 foreach ( $magic->getSynonyms() as $i => $syn ) {
111 if ( $capture ) {
112 // Group name must start with a non-digit in PCRE 8.34+
113 $it = strtr( $i, '0123456789', 'abcdefghij' );
114 $groupName = $it . '_' . $name;
115 $group = '(?P<' . $groupName . '>' . preg_quote( $syn, $delimiter ) . ')';
116 $regex[$case][] = $group;
117 } else {
118 $regex[$case][] = preg_quote( $syn, $delimiter );
119 }
120 }
121 }
122 '@phan-var array<int,string[]> $regex';
123 foreach ( $regex as $case => &$re ) {
124 $re = count( $re ) ? implode( '|', $re ) : '(?!)';
125 if ( !$case ) {
126 $re = "(?i:{$re})";
127 }
128 }
129 '@phan-var array<int,string> $regex';
130
131 if ( $capture && $delimiter === '/' ) {
132 $this->baseRegex = $regex;
133 }
134 return $regex;
135 }
136
142 private function getRegex(): array {
143 if ( $this->regex === null ) {
144 $this->regex = [];
145 $base = $this->getBaseRegex( true, '/' );
146 foreach ( $base as $case => $re ) {
147 $this->regex[$case] = "/$re/JS";
148 }
149 // As a performance optimization, turn on unicode mode only for
150 // case-insensitive matching.
151 $this->regex[0] .= 'u';
152 }
153 return $this->regex;
154 }
155
161 private function getRegexStart(): array {
162 $newRegex = [];
163 $base = $this->getBaseRegex( true, '/' );
164 foreach ( $base as $case => $re ) {
165 $newRegex[$case] = "/^(?:$re)/JS";
166 }
167 // As a performance optimization, turn on unicode mode only for
168 // case-insensitive matching.
169 $newRegex[0] .= 'u';
170 return $newRegex;
171 }
172
178 private function getVariableStartToEndRegex(): array {
179 $newRegex = [];
180 $base = $this->getBaseRegex( true, '/' );
181 foreach ( $base as $case => $re ) {
182 $newRegex[$case] = str_replace( '\$1', '(.*?)', "/^(?:$re)$/JS" );
183 }
184 // As a performance optimization, turn on unicode mode only for
185 // case-insensitive matching.
186 $newRegex[0] .= 'u';
187 return $newRegex;
188 }
189
194 public function getNames() {
195 return $this->names;
196 }
197
205 private function parseMatch( array $matches ): array {
206 $magicName = null;
207 foreach ( $matches as $key => $match ) {
208 if ( $magicName !== null ) {
209 // The structure we found at this point is [ …,
210 // 'a_magicWordName' => 'matchedSynonym',
211 // n => 'matchedSynonym (again)',
212 // n + 1 => 'parameterValue',
213 // … ]
214 return [ $magicName, $matches[$key + 1] ?? false ];
215 }
216 // Skip the initial full match and any non-matching group
217 if ( $match !== '' && $key !== 0 ) {
218 $parts = explode( '_', $key, 2 );
219 if ( !isset( $parts[1] ) ) {
220 throw new LogicException( 'Unexpected group name' );
221 }
222 $magicName = $parts[1];
223 }
224 }
225 throw new LogicException( 'Unexpected $m array with no match' );
226 }
227
235 public function matchVariableStartToEnd( $text ): array {
236 $regexes = $this->getVariableStartToEndRegex();
237 foreach ( $regexes as $regex ) {
238 $m = [];
239 if ( preg_match( $regex, $text, $m ) ) {
240 return $this->parseMatch( $m );
241 }
242 }
243 return [ false, false ];
244 }
245
253 public function matchStartToEnd( $text ) {
254 $hash = $this->getHash();
255 if ( isset( $hash[1][$text] ) ) {
256 return $hash[1][$text];
257 }
258 $lc = $this->factory->getContentLanguage()->lc( $text );
259 return $hash[0][$lc] ?? false;
260 }
261
272 public function matchAndRemove( &$text ): array {
273 $found = [];
274 $regexes = $this->getRegex();
275 foreach ( $regexes as $regex ) {
276 $matches = [];
277 $res = preg_match_all( $regex, $text, $matches, PREG_SET_ORDER );
278 if ( $res === false ) {
279 $error = preg_last_error();
280 $errorText = preg_last_error_msg();
281 LoggerFactory::getInstance( 'parser' )->warning( 'preg_match_all error: {code} {errorText}', [
282 'code' => $error,
283 'regex' => $regex,
284 'text' => $text,
285 'errorText' => $errorText
286 ] );
287 // T321234: Don't try to fix old revisions with broken UTF-8, just return as is
288 if ( $error === PREG_BAD_UTF8_ERROR ) {
289 continue;
290 }
291 throw new LogicException( "preg_match_all error $error: $errorText" );
292 } elseif ( $res ) {
293 foreach ( $matches as $m ) {
294 [ $name, $param ] = $this->parseMatch( $m );
295 $found[$name] = $param;
296 }
297 }
298 $res = preg_replace( $regex, '', $text );
299 if ( $res === null ) {
300 $error = preg_last_error();
301 $errorText = preg_last_error_msg();
302 LoggerFactory::getInstance( 'parser' )->warning( 'preg_replace error: {code} {errorText}', [
303 'code' => $error,
304 'regex' => $regex,
305 'text' => $text,
306 'errorText' => $errorText
307 ] );
308 throw new LogicException( "preg_replace error $error: $errorText" );
309 }
310 $text = $res;
311 }
312 return $found;
313 }
314
325 public function matchStartAndRemove( &$text ) {
326 $regexes = $this->getRegexStart();
327 foreach ( $regexes as $regex ) {
328 if ( preg_match( $regex, $text, $m ) ) {
329 [ $id, ] = $this->parseMatch( $m );
330 if ( strlen( $m[0] ) >= strlen( $text ) ) {
331 $text = '';
332 } else {
333 $text = substr( $text, strlen( $m[0] ) );
334 }
335 return $id;
336 }
337 }
338 return false;
339 }
340}
341
343class_alias( MagicWordArray::class, 'MagicWordArray' );
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:81
Create PSR-3 logger objects.
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Class for handling an array of magic words.
matchVariableStartToEnd( $text)
Match some text, with parameter capture.
matchAndRemove(&$text)
Return an associative array for all items that match.
matchStartAndRemove(&$text)
Return the ID of the magic word at the start of $text, and remove the prefix from $text.
getBaseRegex(bool $capture=true, string $delimiter='/')
Get the base regex.
__construct( $names=[], MagicWordFactory $factory=null)
matchStartToEnd( $text)
Match some text, without parameter capture.
add( $name)
Add a magic word by name.
getHash()
Get a 2-d hashtable for this array.
Store information about magic words, and create/cache MagicWord objects.