Last active
September 29, 2017 17:23
-
-
Save helsont/d5f403ae79243a8006417d9ff2121c80 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
public function assertKeys($expected, $array) | |
{ | |
// we want to find if there are differences between the expected keys | |
// and what the $array has provided. array_diff_key does the job but | |
// it is incomplete because it is unidirectional: | |
// | |
// array_diff_key(['a', 'b'], []) !== array_diff_key([], ['a', 'b']); | |
// [] !== ['a', 'b'] | |
// | |
// to fix this, we need to perform the operation in the reverse direction. | |
// however, some keys may appear twice. so we merge the two array and then | |
// find the unique values. | |
// | |
// why not union? a union "+" operation messes with the indices of an | |
// array and will return unexpected values. | |
$result1 = array_diff_key($expected, $array); | |
$result2 = array_diff_key($array, $expected); | |
$result = array_unique(array_merge($result1, $result2)); | |
if (count($result) > 0) { | |
return $result; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment