Completed
Push — 2.x ( f49b88...9f2b65 )
by Leszek
15:52 queued 15:50
created

ListPatcher::patch()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 14
cts 14
cp 1
rs 8.5906
c 0
b 0
f 0
cc 6
eloc 14
nc 10
nop 2
crap 6
1
<?php
2
3
namespace Diff\Patcher;
4
5
use Diff\DiffOp\Diff\Diff;
6
use Diff\DiffOp\DiffOpAdd;
7
use Diff\DiffOp\DiffOpRemove;
8
9
/**
10
 * @since 0.4
11
 *
12
 * @license GPL-2.0+
13
 * @author Jeroen De Dauw < [email protected] >
14
 */
15
class ListPatcher extends ThrowingPatcher {
16
17
	/**
18
	 * @see Patcher::patch
19
	 *
20
	 * Applies the provided diff to the provided array and returns the result.
21
	 * The provided diff needs to be non-associative. In other words, calling
22
	 * isAssociative on it should return false.
23
	 *
24
	 * Note that remove operations can introduce gaps into the input array $base.
25
	 * For instance, when the input is [ 0 => 'a', 1 => 'b', 2 => 'c' ], and there
26
	 * is one remove operation for 'b', the result will be [ 0 => 'a', 2 => 'c' ].
27
	 *
28
	 * @since 0.4
29
	 *
30
	 * @param array $base
31
	 * @param Diff $diff
32
	 *
33
	 * @return array
34
	 * @throws PatcherException
35
	 */
36 16
	public function patch( array $base, Diff $diff ) {
37 16
		if ( $diff->looksAssociative() ) {
38 1
			$this->handleError( 'ListPatcher can only patch using non-associative diffs' );
39
		}
40
41 16
		foreach ( $diff as $diffOp ) {
42 11
			if ( $diffOp instanceof DiffOpAdd ) {
43 8
				$base[] = $diffOp->getNewValue();
44 7
			} elseif ( $diffOp instanceof DiffOpRemove ) {
45 7
				$needle = $diffOp->getOldValue();
46 7
				$key = array_search( $needle, $base, !is_object( $needle ) );
47
48 7
				if ( $key === false ) {
49 2
					$this->handleError( 'Cannot remove an element from a list if it is not present' );
50 2
					continue;
51
				}
52
53 10
				unset( $base[$key] );
54
			}
55
		}
56
57 16
		return $base;
58
	}
59
60
}
61