Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
EscapeCharacterValidator.php
1<?php
2declare( strict_types = 1 );
3
4namespace MediaWiki\Extension\Translate\Validation\Validators;
5
6use InvalidArgumentException;
10use TMessage;
11
19 protected $allowedCharacters;
21 protected $regex;
22
24 private const VALID_CHARS = [ '\t', '\n', '\\\'', '\"', '\f', '\r', '\a', '\b', '\\\\' ];
25
26 public function __construct( array $params ) {
27 $this->allowedCharacters = $params['values'] ?? [];
28
29 if ( $this->allowedCharacters === [] || !is_array( $this->allowedCharacters ) ) {
30 throw new InvalidArgumentException(
31 'No values provided for EscapeCharacter validator.'
32 );
33 }
34
35 $this->regex = $this->buildRegex( $this->allowedCharacters );
36 }
37
38 public function getIssues( TMessage $message, string $targetLanguage ): ValidationIssues {
39 $issues = new ValidationIssues();
40 $translation = $message->translation();
41 preg_match_all( "/$this->regex/U", $translation, $transVars );
42
43 // Check for missing variables in the translation
44 $params = $transVars[0];
45 if ( count( $params ) ) {
46 $messageParams = [
47 [ 'PARAMS', $params ],
48 [ 'COUNT', count( $params ) ],
49 [ 'PARAMS', $this->allowedCharacters ],
50 [ 'COUNT', count( $this->allowedCharacters ) ]
51 ];
52
53 $issue =
55 'escape', 'invalid', 'translate-checks-escape', $messageParams
56 );
57 $issues->add( $issue );
58 }
59
60 return $issues;
61 }
62
63 private function buildRegex( array $allowedCharacters ): string {
64 $regex = '\\\\[^';
65 $prefix = '';
66 foreach ( $allowedCharacters as $character ) {
67 if ( !in_array( $character, self::VALID_CHARS ) ) {
68 throw new InvalidArgumentException(
69 "Invalid escape character encountered: $character during configuration." .
70 'Valid escape characters include: ' . implode( ', ', self::VALID_CHARS )
71 );
72 }
73
74 if ( $character !== '\\' ) {
75 $character = stripslashes( $character );
76 // negative look ahead, to avoid "\\ " being treated as an accidental escape
77 $prefix = '(?<!\\\\)';
78 }
79
80 // This is done because in the regex we need slashes for some characters such as
81 // \", \', but not for others such as \n, \t etc
82 $normalizedChar = addslashes( $character );
83 $regex .= $normalizedChar;
84 }
85 $regex .= ']';
86
87 return $prefix . $regex;
88 }
89}
Ensures that only the specified escape characters are present.
Interface for message objects used by MessageCollection.
Definition Message.php:14
translation()
Get the message translation.