diff --git a/src/ArrayComparator.php b/src/ArrayComparator.php index 07eba9d3..35a83e07 100644 --- a/src/ArrayComparator.php +++ b/src/ArrayComparator.php @@ -9,9 +9,11 @@ */ namespace SebastianBergmann\Comparator; +use function array_is_list; use function array_key_exists; use function assert; use function is_array; +use function ksort; use function sort; use function sprintf; use function str_replace; @@ -39,8 +41,8 @@ public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0, assert(is_array($actual)); if ($canonicalize) { - sort($expected); - sort($actual); + $this->canonicalize($expected); + $this->canonicalize($actual); } $remaining = $actual; @@ -124,4 +126,13 @@ private function indent(string $lines): string { return trim(str_replace("\n", "\n ", $lines)); } + + private function canonicalize(array &$array): void + { + if (array_is_list($array)) { + sort($array); + } else { + ksort($array); + } + } } diff --git a/tests/ArrayComparatorTest.php b/tests/ArrayComparatorTest.php index e1c2389a..0534ed2c 100644 --- a/tests/ArrayComparatorTest.php +++ b/tests/ArrayComparatorTest.php @@ -70,6 +70,12 @@ public static function assertEqualsSucceedsProvider() ['true'], [true], ], + [ + ['a', 'b' => [1, 2], 'c' => [1, 2, 'd' => [1, 2]]], + ['c' => [1, 'd' => [2, 1], 2], 'b' => [2, 1], 'a'], + 0, + true, + ], ]; } @@ -115,6 +121,12 @@ public static function assertEqualsFailsProvider() ['false'], [false], ], + [ + ['a', 'b' => [1, 2]], + ['b' => [2, 1], 'a', 'c' => 3], + 0, + true, + ], ]; }