Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
ValidationRunner.php
Go to the documentation of this file.
1<?php
12namespace MediaWiki\Extension\Translate\Validation;
13
14use Exception;
15use FormatJson;
16use InvalidArgumentException;
20use RuntimeException;
21use TMessage;
22
41 protected $validators = [];
43 protected $groupId;
45 private static $ignorePatterns;
46
47 public function __construct( string $groupId ) {
48 if ( self::$ignorePatterns === null ) {
49 // TODO: Review if this logic belongs in this class.
50 self::reloadIgnorePatterns();
51 }
52
53 $this->groupId = $groupId;
54 }
55
57 protected static function foldValue( string $value ): string {
58 return str_replace( ' ', '_', strtolower( $value ) );
59 }
60
69 public function setValidators( array $validatorConfigs ): void {
70 $this->validators = [];
71 foreach ( $validatorConfigs as $config ) {
72 $this->addValidator( $config );
73 }
74 }
75
77 public function addValidator( array $validatorConfig ): void {
78 $validatorId = $validatorConfig['id'] ?? null;
79 $className = $validatorConfig['class'] ?? null;
80
81 if ( $validatorId !== null ) {
82 $validator = ValidatorFactory::get(
83 $validatorId,
84 $validatorConfig['params'] ?? null
85 );
86 } elseif ( $className !== null ) {
87 $validator = ValidatorFactory::loadInstance(
88 $className,
89 $validatorConfig['params'] ?? null
90 );
91 } else {
92 throw new InvalidArgumentException(
93 'Validator configuration does not specify the \'class\' or \'id\'.'
94 );
95 }
96
97 $isInsertable = $validatorConfig['insertable'] ?? false;
98 if ( $isInsertable && !$validator instanceof InsertablesSuggester ) {
99 $actualClassName = get_class( $validator );
100 throw new InvalidArgumentException(
101 "Insertable validator $actualClassName does not implement InsertablesSuggester interface."
102 );
103 }
104
105 $this->validators[] = [
106 'instance' => $validator,
107 'insertable' => $isInsertable,
108 'enforce' => $validatorConfig['enforce'] ?? false,
109 'include' => $validatorConfig['keymatch'] ?? $validatorConfig['include'] ?? false,
110 'exclude' => $validatorConfig['exclude'] ?? false
111 ];
112 }
113
119 public function getValidators(): array {
120 return array_map(
121 static function ( $validator ) {
122 return $validator['instance'];
123 },
124 $this->validators
125 );
126 }
127
134 public function getInsertableValidators(): array {
135 $insertableValidators = [];
136 foreach ( $this->validators as $validator ) {
137 if ( $validator['insertable'] === true ) {
138 $insertableValidators[] = $validator['instance'];
139 }
140 }
141
142 return $insertableValidators;
143 }
144
150 public function validateMessage(
151 TMessage $message,
152 string $code,
153 bool $ignoreWarnings = false
155 $errors = new ValidationIssues();
156 $warnings = new ValidationIssues();
157
158 foreach ( $this->validators as $validator ) {
159 $this->runValidation(
160 $validator,
161 $message,
162 $code,
163 $errors,
164 $warnings,
165 $ignoreWarnings
166 );
167 }
168
169 $errors = $this->filterValidations( $message->key(), $errors, $code );
170 $warnings = $this->filterValidations( $message->key(), $warnings, $code );
171
172 return new ValidationResult( $errors, $warnings );
173 }
174
176 public function quickValidate(
177 TMessage $message,
178 string $code,
179 bool $ignoreWarnings = false
181 $errors = new ValidationIssues();
182 $warnings = new ValidationIssues();
183
184 foreach ( $this->validators as $validator ) {
185 $this->runValidation(
186 $validator,
187 $message,
188 $code,
189 $errors,
190 $warnings,
191 $ignoreWarnings
192 );
193
194 $errors = $this->filterValidations( $message->key(), $errors, $code );
195 $warnings = $this->filterValidations( $message->key(), $warnings, $code );
196
197 if ( $warnings->hasIssues() || $errors->hasIssues() ) {
198 break;
199 }
200 }
201
202 return new ValidationResult( $errors, $warnings );
203 }
204
206 public static function reloadIgnorePatterns(): void {
207 $validationExclusionFile = Services::getInstance()->getConfigHelper()->getValidationExclusionFile();
208
209 if ( $validationExclusionFile === false ) {
210 self::$ignorePatterns = [];
211 return;
212 }
213
214 $list = PHPVariableLoader::loadVariableFromPHPFile(
215 $validationExclusionFile,
216 'validationExclusionList'
217 );
218 $keys = [ 'group', 'check', 'subcheck', 'code', 'message' ];
219
220 if ( $list && !is_array( $list ) ) {
221 throw new InvalidArgumentException(
222 "validationExclusionList defined in $validationExclusionFile must be an array"
223 );
224 }
225
226 foreach ( $list as $key => $pattern ) {
227 foreach ( $keys as $checkKey ) {
228 if ( !isset( $pattern[$checkKey] ) ) {
229 $list[$key][$checkKey] = '#';
230 } elseif ( is_array( $pattern[$checkKey] ) ) {
231 $list[$key][$checkKey] =
232 array_map(
233 [ self::class, 'foldValue' ],
234 $pattern[$checkKey]
235 );
236 } else {
237 $list[$key][$checkKey] = self::foldValue( $pattern[$checkKey] );
238 }
239 }
240 }
241
242 self::$ignorePatterns = $list;
243 }
244
246 private function filterValidations(
247 string $messageKey,
248 ValidationIssues $issues,
249 string $targetLanguage
250 ): ValidationIssues {
251 $filteredIssues = new ValidationIssues();
252
253 foreach ( $issues as $issue ) {
254 foreach ( self::$ignorePatterns as $pattern ) {
255 if ( $this->shouldIgnore( $messageKey, $issue, $this->groupId, $targetLanguage, $pattern ) ) {
256 continue 2;
257 }
258 }
259 $filteredIssues->add( $issue );
260 }
261
262 return $filteredIssues;
263 }
264
265 private function shouldIgnore(
266 string $messageKey,
267 ValidationIssue $issue,
268 string $messageGroupId,
269 string $targetLanguage,
270 array $pattern
271 ): bool {
272 return $this->matchesIgnorePattern( $pattern['group'], $messageGroupId )
273 && $this->matchesIgnorePattern( $pattern['check'], $issue->type() )
274 && $this->matchesIgnorePattern( $pattern['subcheck'], $issue->subType() )
275 && $this->matchesIgnorePattern( $pattern['message'], $messageKey )
276 && $this->matchesIgnorePattern( $pattern['code'], $targetLanguage );
277 }
278
286 private function matchesIgnorePattern( $pattern, string $value ): bool {
287 if ( $pattern === '#' ) {
288 return true;
289 } elseif ( is_array( $pattern ) ) {
290 return in_array( strtolower( $value ), $pattern, true );
291 } else {
292 return strtolower( $value ) === $pattern;
293 }
294 }
295
304 protected function doesKeyMatch( string $key, array $keyMatches ): bool {
305 $normalizedKey = lcfirst( $key );
306 foreach ( $keyMatches as $match ) {
307 if ( is_string( $match ) ) {
308 if ( lcfirst( $match ) === $normalizedKey ) {
309 return true;
310 }
311 continue;
312 }
313
314 // The value is neither a string nor an array, should never happen but still handle it.
315 if ( !is_array( $match ) ) {
316 throw new InvalidArgumentException(
317 "Invalid key matcher configuration passed. Expected type: array or string. " .
318 "Received: " . gettype( $match ) . ". match value: " . FormatJson::encode( $match )
319 );
320 }
321
322 $matcherType = $match['type'];
323 $pattern = $match['pattern'];
324
325 // If regex matches, or wildcard matches return true, else continue processing.
326 if (
327 ( $matcherType === 'regex' && preg_match( $pattern, $normalizedKey ) === 1 ) ||
328 ( $matcherType === 'wildcard' && fnmatch( $pattern, $normalizedKey ) )
329 ) {
330 return true;
331 }
332 }
333
334 return false;
335 }
336
342 private function runValidation(
343 array $validatorData,
344 TMessage $message,
345 string $targetLanguage,
346 ValidationIssues $errors,
347 ValidationIssues $warnings,
348 bool $ignoreWarnings
349 ): void {
350 // Check if key match has been specified, and then check if the key matches it.
352 $validator = $validatorData['instance'];
353
354 $definition = $message->definition();
355 if ( $definition === null ) {
356 // This should NOT happen, but add a check since it seems to be happening
357 // See: https://phabricator.wikimedia.org/T255669
358 return;
359 }
360
361 try {
362 $includedKeys = $validatorData['include'];
363 if ( $includedKeys !== false && !$this->doesKeyMatch( $message->key(), $includedKeys ) ) {
364 return;
365 }
366
367 $excludedKeys = $validatorData['exclude'];
368 if ( $excludedKeys !== false && $this->doesKeyMatch( $message->key(), $excludedKeys ) ) {
369 return;
370 }
371
372 if ( $validatorData['enforce'] === true ) {
373 $errors->merge( $validator->getIssues( $message, $targetLanguage ) );
374 } elseif ( !$ignoreWarnings ) {
375 $warnings->merge( $validator->getIssues( $message, $targetLanguage ) );
376 }
377 // else: caller does not want warnings, skip running the validator
378 } catch ( Exception $e ) {
379 throw new RuntimeException(
380 'An error occurred while validating message: ' . $message->key() . '; group: ' .
381 $this->groupId . "; validator: " . get_class( $validator ) . "\n. Exception: $e"
382 );
383 }
384 }
385}
return[ 'Translate:ConfigHelper'=> static function():ConfigHelper { return new ConfigHelper();}, 'Translate:CsvTranslationImporter'=> static function(MediaWikiServices $services):CsvTranslationImporter { return new CsvTranslationImporter( $services->getWikiPageFactory());}, 'Translate:EntitySearch'=> static function(MediaWikiServices $services):EntitySearch { return new EntitySearch($services->getMainWANObjectCache(), $services->getCollationFactory() ->makeCollation( 'uca-default-u-kn'), MessageGroups::singleton(), $services->getNamespaceInfo(), $services->get( 'Translate:MessageIndex'), $services->getTitleParser(), $services->getTitleFormatter());}, 'Translate:ExternalMessageSourceStateImporter'=> static function(MediaWikiServices $services):ExternalMessageSourceStateImporter { return new ExternalMessageSourceStateImporter($services->getMainConfig(), $services->get( 'Translate:GroupSynchronizationCache'), $services->getJobQueueGroup(), LoggerFactory::getInstance( 'Translate.GroupSynchronization'), MessageIndex::singleton());}, 'Translate:GroupSynchronizationCache'=> static function(MediaWikiServices $services):GroupSynchronizationCache { return new GroupSynchronizationCache( $services->get( 'Translate:PersistentCache'));}, 'Translate:MessageBundleStore'=> static function(MediaWikiServices $services):MessageBundleStore { return new MessageBundleStore(new RevTagStore(), $services->getJobQueueGroup(), $services->getLanguageNameUtils(), $services->get( 'Translate:MessageIndex'));}, 'Translate:MessageGroupReview'=> static function(MediaWikiServices $services):MessageGroupReview { return new MessageGroupReview($services->getDBLoadBalancer(), $services->getHookContainer());}, 'Translate:MessageIndex'=> static function(MediaWikiServices $services):MessageIndex { $params=$services->getMainConfig() ->get( 'TranslateMessageIndex');if(is_string( $params)) { $params=(array) $params;} $class=array_shift( $params);return new $class( $params);}, 'Translate:ParsingPlaceholderFactory'=> static function():ParsingPlaceholderFactory { return new ParsingPlaceholderFactory();}, 'Translate:PersistentCache'=> static function(MediaWikiServices $services):PersistentCache { return new PersistentDatabaseCache($services->getDBLoadBalancer(), $services->getJsonCodec());}, 'Translate:ProgressStatsTableFactory'=> static function(MediaWikiServices $services):ProgressStatsTableFactory { return new ProgressStatsTableFactory($services->getLinkRenderer(), $services->get( 'Translate:ConfigHelper'));}, 'Translate:SubpageListBuilder'=> static function(MediaWikiServices $services):SubpageListBuilder { return new SubpageListBuilder($services->get( 'Translate:TranslatableBundleFactory'), $services->getLinkBatchFactory());}, 'Translate:TranslatableBundleFactory'=> static function(MediaWikiServices $services):TranslatableBundleFactory { return new TranslatableBundleFactory($services->get( 'Translate:TranslatablePageStore'), $services->get( 'Translate:MessageBundleStore'));}, 'Translate:TranslatableBundleMover'=> static function(MediaWikiServices $services):TranslatableBundleMover { return new TranslatableBundleMover($services->getMovePageFactory(), $services->getJobQueueGroup(), $services->getLinkBatchFactory(), $services->get( 'Translate:TranslatableBundleFactory'), $services->get( 'Translate:SubpageListBuilder'), $services->getMainConfig() ->get( 'TranslatePageMoveLimit'));}, 'Translate:TranslatablePageParser'=> static function(MediaWikiServices $services):TranslatablePageParser { return new TranslatablePageParser($services->get( 'Translate:ParsingPlaceholderFactory'));}, 'Translate:TranslatablePageStore'=> static function(MediaWikiServices $services):TranslatablePageStore { return new TranslatablePageStore($services->get( 'Translate:MessageIndex'), $services->getJobQueueGroup(), new RevTagStore(), $services->getDBLoadBalancer());}, 'Translate:TranslationStashReader'=> static function(MediaWikiServices $services):TranslationStashReader { $db=$services->getDBLoadBalancer() ->getConnectionRef(DB_REPLICA);return new TranslationStashStorage( $db);}, 'Translate:TranslationStatsDataProvider'=> static function(MediaWikiServices $services):TranslationStatsDataProvider { return new TranslationStatsDataProvider(new ServiceOptions(TranslationStatsDataProvider::CONSTRUCTOR_OPTIONS, $services->getMainConfig()), $services->getObjectFactory());}, 'Translate:TranslationUnitStoreFactory'=> static function(MediaWikiServices $services):TranslationUnitStoreFactory { return new TranslationUnitStoreFactory( $services->getDBLoadBalancer());}, 'Translate:TranslatorActivity'=> static function(MediaWikiServices $services):TranslatorActivity { $query=new TranslatorActivityQuery($services->getMainConfig(), $services->getDBLoadBalancer());return new TranslatorActivity($services->getMainObjectStash(), $query, $services->getJobQueueGroup());}, 'Translate:TtmServerFactory'=> static function(MediaWikiServices $services):TtmServerFactory { $config=$services->getMainConfig();$default=$config->get( 'TranslateTranslationDefaultService');if( $default===false) { $default=null;} return new TtmServerFactory( $config->get( 'TranslateTranslationServices'), $default);}]
@phpcs-require-sorted-array
Minimal service container.
Definition Services.php:38
Container for validation issues returned by MessageValidator.
Message validator is used to run validators to find common mistakes so that translators can fix them ...
static foldValue(string $value)
Normalise validator keys.
getValidators()
Return the currently set validators for this group.
addValidator(array $validatorConfig)
Add a validator for this group.
validateMessage(TMessage $message, string $code, bool $ignoreWarnings=false)
Validate a translation of a message.
setValidators(array $validatorConfigs)
Set the validators for this group.
getInsertableValidators()
Return currently set validators that are insertable.
quickValidate(TMessage $message, string $code, bool $ignoreWarnings=false)
Validate a message, and return as soon as any validation fails.
doesKeyMatch(string $key, array $keyMatches)
Check if key matches validator's key patterns.
Stuff for handling configuration files in PHP format.
Interface for message objects used by MessageCollection.
Definition Message.php:14
definition()
Get the message definition.
Definition Message.php:51
key()
Get the message key.
Definition Message.php:43