-
Notifications
You must be signed in to change notification settings - Fork 15
/
OrderedArrayComparer.php
70 lines (57 loc) · 1.48 KB
/
OrderedArrayComparer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
declare( strict_types = 1 );
namespace Diff\ArrayComparer;
use Diff\Comparer\ValueComparer;
/**
* Computes the difference between two ordered arrays by comparing elements with
* a ValueComparer.
*
* Quantity matters: [42, 42] and [42] are different
* Order matters: [42, 43] and [43, 42] are different
*
* @since 0.9
*
* @license BSD-3-Clause
* @author Jeroen De Dauw < [email protected] >
* @author Tobias Gritschacher < [email protected] >
*/
class OrderedArrayComparer implements ArrayComparer {
private $valueComparer;
public function __construct( ValueComparer $valueComparer ) {
$this->valueComparer = $valueComparer;
}
/**
* @see ArrayComparer::diffArrays
*
* @since 0.9
*
* @param array $arrayOne
* @param array $arrayTwo
*
* @return array
*/
public function diffArrays( array $arrayOne, array $arrayTwo ): array {
$notInTwo = [];
foreach ( $arrayOne as $valueOffset => $element ) {
if ( !$this->arraySearch( $element, $arrayTwo, $valueOffset ) ) {
$notInTwo[] = $element;
continue;
}
unset( $arrayTwo[$valueOffset] );
}
return $notInTwo;
}
/**
* @param string|int $needle
* @param array $haystack
* @param int|string $valueOffset
*
* @return bool
*/
private function arraySearch( $needle, array $haystack, $valueOffset ): bool {
if ( array_key_exists( $valueOffset, $haystack ) ) {
return $this->valueComparer->valuesAreEqual( $needle, $haystack[$valueOffset] );
}
return false;
}
}