summaryrefslogtreecommitdiff
blob: b9f51caf20e54db4cdc9a100f3a8a382a0f63149 (plain)
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
<?php
/**
 * Contains a class to track changes to the messages when importing messages from remote source.
 * @author Abijeet Patro
 * @license GPL-2.0-or-later
 * @file
 */

namespace MediaWiki\Extensions\Translate\MessageSync;

use InvalidArgumentException;

/**
 * Class is use to track the changes made when importing messages from the remote sources
 * using processMessageChanges. Also provides an interface to query these changes, and
 * update them.
 * @since 2019.10
 */
class MessageSourceChange {
	/**
	 * @var array[][][]
	 * @codingStandardsIgnoreStart
	 * @phan-var array<string,array<string,array<string|int,array{key:string,content:string,similarity?:float,matched_to?:string,previous_state?:string}>>>
	 * @codingStandardsIgnoreEnd
	 */
	protected $changes = [];

	public const ADDITION = 'addition';
	public const CHANGE = 'change';
	public const DELETION = 'deletion';
	public const RENAME = 'rename';
	public const NONE = 'none';

	private const SIMILARITY_THRESHOLD = 0.9;

	/**
	 * Contains a mapping of mesasge type, and the corresponding addition function
	 * @var callable[]
	 */
	protected $addFunctionMap;

	/**
	 * Contains a mapping of message type, and the corresponding removal function
	 * @var callable[]
	 */
	protected $removeFunctionMap;

	/**
	 * @param array[][][] $changes
	 */
	public function __construct( $changes = [] ) {
		$this->changes = $changes;
		$this->addFunctionMap = [
			self::ADDITION => [ $this, 'addAddition' ],
			self::DELETION => [ $this, 'addDeletion' ],
			self::CHANGE => [ $this, 'addChange' ]
		];

		$this->removeFunctionMap = [
			self::ADDITION => [ $this, 'removeAdditions' ],
			self::DELETION => [ $this, 'removeDeletions' ],
			self::CHANGE => [ $this, 'removeChanges' ]
		];
	}

	/**
	 * Add a change under a message group for a specific language
	 * @param string $language
	 * @param string $key
	 * @param string $content
	 */
	public function addChange( $language, $key, $content ) {
		$this->addModification( $language, self::CHANGE, $key, $content );
	}

	/**
	 * Add an addition under a message group for a specific language
	 * @param string $language
	 * @param string $key
	 * @param string $content
	 */
	public function addAddition( $language, $key, $content ) {
		$this->addModification( $language, self::ADDITION, $key, $content );
	}

	/**
	 * Adds a deletion under a message group for a specific language
	 * @param string $language
	 * @param string $key
	 * @param string $content
	 */
	public function addDeletion( $language, $key, $content ) {
		$this->addModification( $language, self::DELETION, $key, $content );
	}

	/**
	 * Adds a rename under a message group for a specific language
	 * @param string $language
	 * @param string[] $addedMessage
	 * @param string[] $deletedMessage
	 * @param float $similarity
	 */
	public function addRename( $language, $addedMessage, $deletedMessage, $similarity = 0 ) {
		$this->changes[$language][self::RENAME][$addedMessage['key']] = [
			'content' => $addedMessage['content'],
			'similarity' => $similarity,
			'matched_to' => $deletedMessage['key'],
			'previous_state' => self::ADDITION,
			'key' => $addedMessage['key']
		];

		$this->changes[$language][self::RENAME][$deletedMessage['key']] = [
			'content' => $deletedMessage['content'],
			'similarity' => $similarity,
			'matched_to' => $addedMessage['key'],
			'previous_state' => self::DELETION,
			'key' => $deletedMessage['key']
		];
	}

	public function setRenameState( $language, $msgKey, $state ) {
		$possibleStates = [ self::ADDITION, self::CHANGE, self::DELETION,
			self::NONE, self::RENAME ];
		if ( !in_array( $state, $possibleStates ) ) {
			throw new InvalidArgumentException(
				"Invalid state passed - '$state'. Possible states - "
				. implode( ', ', $possibleStates )
			);
		}

		$languageChanges = null;
		if ( isset( $this->changes[ $language ] ) ) {
			$languageChanges = &$this->changes[ $language ];
		}
		if ( $languageChanges !== null && isset( $languageChanges[ 'rename' ][ $msgKey ] ) ) {
			$languageChanges[ 'rename' ][ $msgKey ][ 'previous_state' ] = $state;
		}
	}

	/**
	 * @param string $language
	 * @param string $type
	 * @param string $key
	 * @param string $content
	 */
	protected function addModification( $language, $type, $key, $content ) {
		$this->changes[$language][$type][] = [
			'key' => $key,
			'content' => $content,
		];
	}

	/**
	 * Fetch changes for a message group under a language
	 * @param string $language
	 * @return array[]
	 */
	public function getChanges( $language ) {
		return $this->getModification( $language, self::CHANGE );
	}

	/**
	 * Fetch deletions for a message group under a language
	 * @param string $language
	 * @return array[]
	 */
	public function getDeletions( $language ) {
		return $this->getModification( $language, self::DELETION );
	}

	/**
	 * Fetch additions for a message group under a language
	 * @param string $language
	 * @return array[]
	 */
	public function getAdditions( $language ) {
		return $this->getModification( $language, self::ADDITION );
	}

	/**
	 * Finds a message with the given key across different types of modifications.
	 * @param string $language
	 * @param string $key
	 * @param string[] $possibleStates
	 * @param string|null &$modificationType
	 * @return array|null
	 */
	public function findMessage( $language, $key, $possibleStates = [], &$modificationType = null ) {
		$allChanges = [];
		$allChanges[self::ADDITION] = $this->getAdditions( $language );
		$allChanges[self::DELETION] = $this->getDeletions( $language );
		$allChanges[self::CHANGE] = $this->getChanges( $language );
		$allChanges[self::RENAME] = $this->getRenames( $language );

		if ( $possibleStates === [] ) {
			$possibleStates = [ self::ADDITION, self::CHANGE, self::DELETION, self::RENAME ];
		}

		foreach ( $allChanges as $type => $modifications ) {
			if ( !in_array( $type, $possibleStates ) ) {
				continue;
			}

			if ( $type === self::RENAME ) {
				if ( isset( $modifications[$key] ) ) {
					$modificationType = $type;
					return $modifications[$key];
				}
				continue;
			}

			foreach ( $modifications as $modification ) {
				$currentKey = $modification['key'];
				if ( $currentKey === $key ) {
					$modificationType = $type;
					return $modification;
				}
			}
		}

		$modificationType = null;
		return null;
	}

	/**
	 * Break reanmes, and put messages back into their previous state.
	 * @param string $languageCode
	 * @param string $msgKey
	 * @return string|null previous state of the message
	 */
	public function breakRename( $languageCode, $msgKey ) {
		$msg = $this->findMessage( $languageCode, $msgKey, [ self::RENAME ] );
		if ( $msg === null ) {
			return null;
		}
		$matchedMsg = $this->getMatchedMessage( $languageCode, $msg['key'] );
		if ( $matchedMsg === null ) {
			return null;
		}

		// Remove them from the renames array
		$this->removeRenames( $languageCode, [ $matchedMsg['key'], $msg['key'] ] );

		$matchedMsgState = $matchedMsg[ 'previous_state' ];
		$msgState = $msg[ 'previous_state' ];

		// Add them to the changes under the appropriate state
		if ( $matchedMsgState !== self::NONE ) {
			if ( $matchedMsgState === self::CHANGE ) {
				$matchedMsg['key'] = $msg['key'];
			}
			call_user_func(
				$this->addFunctionMap[ $matchedMsgState ],
				$languageCode,
				$matchedMsg['key'],
				$matchedMsg['content']
			);
		}

		if ( $msgState !== self::NONE ) {
			if ( $msgState === self::CHANGE ) {
				$msg['key'] = $matchedMsg['key'];
			}
			call_user_func(
				$this->addFunctionMap[ $msgState ],
				$languageCode,
				$msg['key'],
				$msg['content']
			);
		}

		return $msgState;
	}

	/**
	 * Fetch renames for a message group under a language
	 * @param string $language
	 * @return array[]
	 */
	public function getRenames( $language ) {
		$renames = $this->getModification( $language, self::RENAME );
		foreach ( $renames as $key => &$rename ) {
			$rename['key'] = $key;
		}

		return $renames;
	}

	/**
	 * @param string $language
	 * @param string $type
	 * @return array[]
	 */
	protected function getModification( $language, $type ) {
		return $this->changes[$language][$type] ?? [];
	}

	/**
	 * Remove additions for a language under the group.
	 * @param string $language
	 * @param array|null $keysToRemove
	 */
	public function removeAdditions( $language, $keysToRemove ) {
		$this->removeModification( $language, self::ADDITION, $keysToRemove );
	}

	/**
	 * Remove deletions for a language under the group.
	 * @param string $language
	 * @param array|null $keysToRemove
	 */
	public function removeDeletions( $language, $keysToRemove ) {
		$this->removeModification( $language, self::DELETION, $keysToRemove );
	}

	/**
	 * Remove changes for a language under the group.
	 * @param string $language
	 * @param array|null $keysToRemove
	 */
	public function removeChanges( $language, $keysToRemove ) {
		$this->removeModification( $language, self::CHANGE, $keysToRemove );
	}

	/**
	 * Remove renames for a language under the group.
	 * @param string $language
	 * @param array|null $keysToRemove
	 */
	public function removeRenames( $language, $keysToRemove ) {
		$this->removeModification( $language, self::RENAME, $keysToRemove );
	}

	/**
	 * Remove modifications based on the type. Avoids usage of ugly if / switch
	 * statement.
	 * @param string $language
	 * @param array $keysToRemove
	 * @param string $type - One of ADDITION, CHANGE, DELETION
	 */
	public function removeBasedOnType( $language, $keysToRemove, $type ) {
		$callable = $this->removeFunctionMap[ $type ] ?? null;

		if ( $callable === null ) {
			throw new InvalidArgumentException( 'Type should be one of ' .
				implode( ', ', [ self::ADDITION, self::CHANGE, self::DELETION ] ) .
				". Invalid type $type passed."
			);
		}

		call_user_func( $callable, $language, $keysToRemove );
	}

	/**
	 * Remove all language related changes for a group.
	 * @param string $language
	 */
	public function removeChangesForLanguage( $language ) {
		unset( $this->changes[ $language ] );
	}

	protected function removeModification( $language, $type, $keysToRemove = null ) {
		if ( !isset( $this->changes[$language][$type] ) ) {
			return;
		}

		if ( $keysToRemove === null ) {
			unset( $this->changes[$language][$type] );
		}

		if ( $keysToRemove === [] ) {
			return;
		}

		if ( $type === self::RENAME ) {
			$this->changes[$language][$type] =
				array_diff_key( $this->changes[$language][$type], array_flip( $keysToRemove ) );
		} else {
			$this->changes[$language][$type] = array_filter(
				$this->changes[$language][$type],
				function ( $change ) use ( $keysToRemove ) {
					if ( in_array( $change['key'], $keysToRemove, true ) ) {
						return false;
					}
					return true;
				}
			);
		}
	}

	/**
	 * Return all modifications for the group.
	 * @return array[][][]
	 */
	public function getAllModifications() {
		return $this->changes;
	}

	/**
	 * Get all for a language under the group.
	 * @param string $language
	 * @return array[][]
	 */
	public function getModificationsForLanguage( $language ) {
		return $this->changes[$language] ?? [];
	}

	/**
	 * Loads the changes, and returns an instance of the class.
	 * @param array $changesData
	 * @return self
	 */
	public static function loadModifications( $changesData ) {
		return new self( $changesData );
	}

	/**
	 * Get all language keys with modifications under the group
	 * @return string[]
	 */
	public function getLanguages() {
		return array_keys( $this->changes );
	}

	/**
	 * Determines if the group has only a certain type of change under a language.
	 *
	 * @param string $language
	 * @param string $type
	 * @return bool
	 */
	public function hasOnly( $language, $type ) {
		$deletions = $this->getDeletions( $language );
		$additions = $this->getAdditions( $language );
		$renames = $this->getRenames( $language );
		$changes = $this->getChanges( $language );
		$hasOnlyAdditions = $hasOnlyRenames =
			$hasOnlyChanges = $hasOnlyDeletions = true;

		if ( $deletions ) {
			$hasOnlyAdditions = $hasOnlyRenames = $hasOnlyChanges = false;
		}

		if ( $renames ) {
			$hasOnlyDeletions = $hasOnlyAdditions = $hasOnlyChanges = false;
		}

		if ( $changes ) {
			$hasOnlyAdditions = $hasOnlyRenames = $hasOnlyDeletions = false;
		}

		if ( $additions ) {
			$hasOnlyDeletions = $hasOnlyRenames = $hasOnlyChanges = false;
		}

		if ( $type === self::DELETION ) {
			$response = $hasOnlyDeletions;
		} elseif ( $type === self::RENAME ) {
			$response = $hasOnlyRenames;
		} elseif ( $type === self::CHANGE ) {
			$response = $hasOnlyChanges;
		} elseif ( $type === self::ADDITION ) {
			$response = $hasOnlyAdditions;
		} else {
			throw new InvalidArgumentException( "Unknown $type passed." );
		}

		return $response;
	}

	/**
	 * Checks if the previous state of a renamed message matches a given value
	 * @param string $languageCode
	 * @param string $key
	 * @param string[] $types
	 * @return bool
	 */
	public function isPreviousState( $languageCode, $key, array $types ) {
		$msg = $this->findMessage( $languageCode, $key, [ self::RENAME ] );

		return isset( $msg['previous_state'] ) && in_array( $msg['previous_state'], $types );
	}

	/**
	 * Get matched rename message for a given key
	 * @param string $languageCode
	 * @param string $key
	 * @return array Matched message if found, else null
	 */
	public function getMatchedMessage( $languageCode, $key ) {
		$matchedKey = $this->getMatchedKey( $languageCode, $key );
		if ( $matchedKey ) {
			return $this->changes[ $languageCode ][ self::RENAME ][ $matchedKey ] ?? null;
		}

		return null;
	}

	/**
	 * Get matched rename key for a given key
	 * @param string $languageCode
	 * @param string $key
	 * @return string|null Matched key if found, else null
	 */
	public function getMatchedKey( $languageCode, $key ) {
		return $this->changes[ $languageCode ][ self::RENAME ][ $key ][ 'matched_to' ] ?? null;
	}

	/**
	 * Returns the calculated similarity for a rename
	 * @param string $languageCode
	 * @param string $key
	 * @return float|null
	 */
	public function getSimilarity( $languageCode, $key ) {
		$msg = $this->findMessage( $languageCode, $key, [ self::RENAME ] );

		return $msg[ 'similarity' ] ?? null;
	}

	/**
	 * Checks if a given key is equal to matched rename message
	 * @param string $languageCode
	 * @param string $key
	 * @return bool
	 */
	public function isEqual( $languageCode, $key ) {
		$msg = $this->findMessage( $languageCode, $key, [ self::RENAME ] );
		return $msg && $this->areStringsEqual( $msg[ 'similarity' ] );
	}

	/**
	 * Checks if a given key is similar to matched rename message
	 *
	 * @param string $languageCode
	 * @param string $key
	 * @return bool
	 */
	public function isSimilar( $languageCode, $key ) {
		$msg = $this->findMessage( $languageCode, $key, [ self::RENAME ] );
		return $msg && $this->areStringsSimilar( $msg[ 'similarity' ] );
	}

	/**
	 * Checks if the similarity percent passed passes the min threshold
	 * @param float $similarity
	 * @return bool
	 */
	public function areStringsSimilar( $similarity ) {
		return $similarity >= self::SIMILARITY_THRESHOLD;
	}

	/**
	 * Checks if the similarity percent passed
	 * @param float $similarity
	 * @return bool
	 */
	public function areStringsEqual( $similarity ) {
		return $similarity === 1;
	}
}