TermListPatcher::patchTerm()   B
last analyzed

Complexity

Conditions 9
Paths 7

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.0555
c 0
b 0
f 0
cc 9
nc 7
nop 3
1
<?php
2
3
namespace Wikibase\DataModel\Services\Diff;
4
5
use Diff\DiffOp\AtomicDiffOp;
6
use Diff\DiffOp\Diff\Diff;
7
use Diff\DiffOp\DiffOpAdd;
8
use Diff\DiffOp\DiffOpChange;
9
use Diff\DiffOp\DiffOpRemove;
10
use Diff\Patcher\PatcherException;
11
use Wikibase\DataModel\Term\TermList;
12
13
/**
14
 * @since 3.6
15
 *
16
 * @license GPL-2.0-or-later
17
 * @author Jeroen De Dauw < [email protected] >
18
 * @author Thiemo Kreuz
19
 */
20
class TermListPatcher {
21
22
	/**
23
	 * @since 3.6
24
	 *
25
	 * @param TermList $terms
26
	 * @param Diff $patch
27
	 *
28
	 * @throws PatcherException
29
	 */
30
	public function patchTermList( TermList $terms, Diff $patch ) {
31
		foreach ( $patch as $lang => $diffOp ) {
32
			$this->patchTerm( $terms, $lang, $diffOp );
33
		}
34
	}
35
36
	/**
37
	 * @see MapPatcher
38
	 *
39
	 * @param TermList $terms
40
	 * @param string $lang
41
	 * @param AtomicDiffOp $diffOp
42
	 *
43
	 * @throws PatcherException
44
	 */
45
	private function patchTerm( TermList $terms, $lang, AtomicDiffOp $diffOp ) {
46
		$hasLang = $terms->hasTermForLanguage( $lang );
47
48
		switch ( true ) {
49
			case $diffOp instanceof DiffOpAdd:
50
				if ( !$hasLang ) {
51
					$terms->setTextForLanguage( $lang, $diffOp->getNewValue() );
52
				}
53
				break;
54
55
			case $diffOp instanceof DiffOpChange:
56
				if ( $hasLang
57
					&& $terms->getByLanguage( $lang )->getText() === $diffOp->getOldValue()
58
				) {
59
					$terms->setTextForLanguage( $lang, $diffOp->getNewValue() );
60
				}
61
				break;
62
63
			case $diffOp instanceof DiffOpRemove:
64
				if ( $hasLang
65
					&& $terms->getByLanguage( $lang )->getText() === $diffOp->getOldValue()
66
				) {
67
					$terms->removeByLanguage( $lang );
68
				}
69
				break;
70
71
			default:
72
				throw new PatcherException( 'Invalid terms diff' );
73
		}
74
	}
75
76
}
77