Completed
Push — master ( c0676d...e5a675 )
by
unknown
24s
created

TermListPatcher::patchTerm()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 33
rs 4.909
cc 9
eloc 19
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+
17
 * @author Jeroen De Dauw < [email protected] >
18
 * @author Thiemo Mättig
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
				/** @var $diffOp DiffOpAdd */
51
				if ( !$hasLang ) {
52
					$terms->setTextForLanguage( $lang, $diffOp->getNewValue() );
53
				}
54
				break;
55
56
			case $diffOp instanceof DiffOpChange:
57
				/** @var $diffOp DiffOpChange */
58
				if ( $hasLang
59
					&& $terms->getByLanguage( $lang )->getText() === $diffOp->getOldValue()
60
				) {
61
					$terms->setTextForLanguage( $lang, $diffOp->getNewValue() );
62
				}
63
				break;
64
65
			case $diffOp instanceof DiffOpRemove:
66
				/** @var $diffOp DiffOpRemove */
67
				if ( $hasLang
68
					&& $terms->getByLanguage( $lang )->getText() === $diffOp->getOldValue()
69
				) {
70
					$terms->removeByLanguage( $lang );
71
				}
72
				break;
73
74
			default:
75
				throw new PatcherException( 'Invalid terms diff' );
76
		}
77
	}
78
79
}
80