Completed
Push — master ( 5bfabc...2f44b9 )
by Jeroen De
02:42
created

StatementListPatcher::changeStatement()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 3
eloc 6
nc 3
nop 3
1
<?php
2
3
namespace Wikibase\DataModel\Services\Diff;
4
5
use Diff\DiffOp\Diff\Diff;
6
use Diff\DiffOp\DiffOp;
7
use Diff\DiffOp\DiffOpAdd;
8
use Diff\DiffOp\DiffOpChange;
9
use Diff\DiffOp\DiffOpRemove;
10
use Diff\Patcher\PatcherException;
11
use Wikibase\DataModel\Statement\Statement;
12
use Wikibase\DataModel\Statement\StatementList;
13
14
/**
15
 * @since 3.6
16
 *
17
 * @license GPL-2.0+
18
 * @author Jeroen De Dauw < [email protected] >
19
 * @author Thiemo Mättig
20
 */
21
class StatementListPatcher {
22
23
	/**
24
	 * @since 3.6
25
	 *
26
	 * @param StatementList $statements
27
	 * @param Diff $patch
28
	 *
29
	 * @throws PatcherException
30
	 */
31
	public function patchStatementList( StatementList $statements, Diff $patch ) {
32
		/** @var DiffOp $diffOp */
33
		foreach ( $patch as $diffOp ) {
34
			switch ( true ) {
35
				case $diffOp instanceof DiffOpAdd:
36
					/** @var DiffOpAdd $diffOp */
37
					/** @var Statement $statement */
38
					$statement = $diffOp->getNewValue();
39
					$guid = $statement->getGuid();
40
					if ( $statements->getFirstStatementWithGuid( $guid ) === null ) {
41
						$statements->addStatement( $statement );
42
					}
43
					break;
44
45
				case $diffOp instanceof DiffOpChange:
46
					/** @var DiffOpChange $diffOp */
47
					/** @var Statement $oldStatement */
48
					/** @var Statement $newStatement */
49
					$oldStatement = $diffOp->getOldValue();
50
					$newStatement = $diffOp->getNewValue();
51
					$this->changeStatement( $statements, $oldStatement->getGuid(), $newStatement );
52
					break;
53
54
				case $diffOp instanceof DiffOpRemove:
55
					/** @var DiffOpRemove $diffOp */
56
					/** @var Statement $statement */
57
					$statement = $diffOp->getOldValue();
58
					$statements->removeStatementsWithGuid( $statement->getGuid() );
59
					break;
60
61
				default:
62
					throw new PatcherException( 'Invalid statement list diff' );
63
			}
64
		}
65
	}
66
67
	/**
68
	 * @param StatementList $statements
69
	 * @param string|null $oldGuid
70
	 * @param Statement $newStatement
71
	 */
72
	private function changeStatement( StatementList $statements, $oldGuid, Statement $newStatement ) {
73
		foreach ( $statements->toArray() as $index => $statement ) {
74
			if ( $statement->getGuid() === $oldGuid ) {
75
				$statements->removeStatementsWithGuid( $oldGuid );
76
				$statements->addStatement( $newStatement, $index );
77
				return;
78
			}
79
		}
80
	}
81
82
}
83