Validate list of keys in the associative array.
@since Method available since Release 3.3.0 @author Mike Naberezny <mike@maintainable.com> @author Derek DeVries <derek@maintainable.com>
array $hash:
array $validKeys:
array
public static function assertValidKeys(array $hash, array $validKeys) {
$valids = array();
// Normalize validation keys so that we can use both indexed and
// associative arrays.
foreach ($validKeys as $key => $val) {
is_int($key) ? $valids[$val] = NULL : ($valids[$key] = $val);
}
$validKeys = array_keys($valids);
// Check for invalid keys.
foreach ($hash as $key => $value) {
if (!in_array($key, $validKeys)) {
$unknown[] = $key;
}
}
if (!empty($unknown)) {
throw new PHPUnit_Framework_Exception('Unknown key(s): ' . implode(', ', $unknown));
}
// Add default values for any valid keys that are empty.
foreach ($valids as $key => $value) {
if (!isset($hash[$key])) {
$hash[$key] = $value;
}
}
return $hash;
}