Skip to content

Instantly share code, notes, and snippets.

@lacri42
Created August 18, 2016 16:25
Show Gist options
  • Save lacri42/b3edec93baeeede34713cec6d67ccee8 to your computer and use it in GitHub Desktop.
Save lacri42/b3edec93baeeede34713cec6d67ccee8 to your computer and use it in GitHub Desktop.
This method checks if an array key exists recursively and returns its value on existence. Optionally validates the value against a callable.
<?php
/**
* This method checks if an array key exists recursively and returns its value on existence.
* Optionally validates the value against a callable.
*
* Example without callable:
* <code>
* $myArray = [
* "foo" => [
* "bar" => [
* "blubb" => "my value"
* ]
* ]
* ];
*
* $value = safeRecursiveArrayAccess($myArray, ["foo", "bar", "blubb"]);
* var_dump($value); // string(8) "my value"
* </code>
*
* Example with internal type-check functions:
* <code>
* $myArray = [
* "foo" => [
* "bar" => [
* "blubb" => "my value"
* ]
* ]
* ];
*
* $value = safeRecursiveArrayAccess($myArray, ["foo", "bar", "blubb"], "is_array");
* //Exception (blubb must be an array but string received)
* </code>
*
* Example with callable validation:
* <code>
* $myArray = [
* "foo" => [
* "bar" => [
* "blubb" => "my value"
* ]
* ]
* ];
*
* $value = safeRecursiveArrayAccess($myArray, ["foo", "bar", "blubb"], function($value) {
* // return true or false
* return myBusinessLogicValidation($value);
* });
* </code>
*
* @param array $array the array you want to access
* @param array $path an array of the keys to walk through recursively in the correct order
* @param callable $validator
*
* @return mixed
* @throws Exception
*/
public function safeRecursiveArrayAccess(array $array, array $path, callable $validator = null)
{
foreach ($path as $key) {
if (false === is_array($array)) {
throw new Exception('The given Key does not exist: ' . $key);
}
if (array_key_exists($key, $array)) {
$array = $array[$key];
} else {
throw new Exception('The given Key does not exist: ' . $key);
}
}
if (!$validator) {
return $array;
}
if (false === $validator($array)) {
throw new Exception(sprintf(
'Invalid Type detected, validated with %s, but received type of %s',
$validator,
gettype($array)
));
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment