Skip to content

Instantly share code, notes, and snippets.

@oojacoboo
Created March 18, 2020 20:25
Show Gist options
  • Save oojacoboo/7ff02d08f865bb6c4e64930f27d43c24 to your computer and use it in GitHub Desktop.
Save oojacoboo/7ff02d08f865bb6c4e64930f27d43c24 to your computer and use it in GitHub Desktop.
/**
* Validates a multi-dimensional array against a default "template"
*
* @param string $settingName
* @param array $templateArray
* @param array $newArray
* @param string $depth
*/
private function validateArrayRecursively(
string $settingName,
array $templateArray,
array $newArray,
string $depth = 'array'
): void
{
foreach ($templateArray as $key => $value) {
if (!\array_key_exists($key, $newArray)) {
throw new InvalidationException(\sprintf('Setting "%s" must have required key "%s[%s]"', $settingName, $depth, $key));
}
if (\gettype($newArray[$key]) !== \gettype($value)) {
throw new InvalidationException(\sprintf(
'Key "%s[%s]" of setting "%s" must be of type "%s", "%s" was found',
$depth,
$key,
$settingName,
\gettype($value),
\gettype($newArray[$key]),
));
}
if (\is_array($value)) {
$this->validateArrayRecursively($settingName, $value, $newArray[$key], $depth . '[' . $key . ']');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment