Created
March 12, 2024 00:23
-
-
Save kmuenkel/7350b133931d07fe33598c22ce32e07f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Recursively compare the content of an array, even if the elements, or nested elements, are out of order | |
*/ | |
function assertArrayContent(array $expected, array $actual, $message = ''): void | |
{ | |
($self = function (array $expected, array $actual, $parentIndex = null) use (&$self, $message): bool { | |
sort($expected); | |
sort($actual); | |
return array_reduce(array_keys($expected), function (bool $equals, $index) use ( | |
$expected, $actual, $self, $parentIndex, $message | |
): bool { | |
$equals &= $expected[$index] === $actual[$index]; | |
$indexPath = $parentIndex === null ? $index : "$parentIndex.$index"; | |
if (!is_array($expected[$index]) && !$equals) { | |
$normalize = fn ($item): string => match ($type = gettype($expected[$index])) { | |
'object' => get_class($expected[$index]), | |
'integer', 'double' => (string) $expected[$index], | |
'boolean' => $expected[$index] ? 'TRUE' : 'FALSE', | |
default => strtoupper($type) | |
}; | |
throw new ExpectationFailedException($message ?: sprintf( | |
'Expected value at "%s", "%s", does not match the given "%s".', | |
$indexPath, $normalize($expected[$index]), $normalize($actual[$index]) | |
)); | |
} | |
return is_array($expected[$index]) ? $self($expected[$index], $actual[$index], $indexPath) : $equals; | |
}, true); | |
})($expected, $actual, $message); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment