From b021fdbabfd730c54cf1f69abd7bd63ee8b898d9 Mon Sep 17 00:00:00 2001 From: Marek Gleska Date: Sun, 11 Aug 2024 13:31:05 +0200 Subject: [PATCH] Fix for issue #112 - ArrayComparator in canonicalize mode --- src/ArrayComparator.php | 10 +++++++-- tests/ArrayComparatorTest.php | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/ArrayComparator.php b/src/ArrayComparator.php index 7550832..b2a4dc6 100644 --- a/src/ArrayComparator.php +++ b/src/ArrayComparator.php @@ -9,6 +9,7 @@ */ namespace SebastianBergmann\Comparator; +use function array_is_list; use function array_key_exists; use function assert; use function is_array; @@ -39,8 +40,13 @@ public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0, assert(is_array($actual)); if ($canonicalize) { - sort($expected); - sort($actual); + if (array_is_list($expected)) { + sort($expected); + } + + if (array_is_list($actual)) { + sort($actual); + } } $remaining = $actual; diff --git a/tests/ArrayComparatorTest.php b/tests/ArrayComparatorTest.php index 8e16b53..07e3de9 100644 --- a/tests/ArrayComparatorTest.php +++ b/tests/ArrayComparatorTest.php @@ -67,6 +67,30 @@ public static function assertEqualsSucceedsProvider(): array ['true'], [true], ], + [ + [1, [1, 2, 3]], + [[3, 1, 2], 1], + 0, + true, + ], + [ + [1, [4, 7], [1, 2, 3], [0, 0, 0, 0]], + [[3, 1, 2], [0, 0, 0, 0], [4, 7], 1], + 0, + true, + ], + [ + [1, [4, [4, 5, 6, 7, 8]], [1, 2, 3]], + [[3, 1, 2], [[4, 8, 6, 7, 5], 4], 1], + 0, + true, + ], + [ + [null, null, 1, 1], + [1, null, 1, null], + 0, + true, + ], ]; } @@ -112,6 +136,24 @@ public static function assertEqualsFailsProvider(): array ['false'], [false], ], + [ + ['a' => '1', 'b' => '2'], + ['c' => '1', 'd' => '2'], + 0, + true, + ], + [ + ['a' => '1', 'b' => '2'], + ['a' => '2', 'b' => '1'], + 0, + true, + ], + [ + ['a' => '1', 'b' => '2'], + ['a' => '1', 'b' => '2', 'c' => '2'], + 0, + true, + ], ]; }