Passed
Push — master ( b37527...aa9965 )
by Jeroen De
42s
created

ListPatcher   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 4
dl 0
loc 45
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

1 Method

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