Created
November 11, 2018 09:54
-
-
Save jdiglesias/b5e3f34d5b2a9d589a8a882dd15fb56e to your computer and use it in GitHub Desktop.
Find value within Drupal 8 render array
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 | |
/** | |
* I got tired of clicking through render arrays displayed in Kint looking for a | |
* specific string. So I wrote this function to find all instances of that string | |
* and give me back a copy-pasteable index for each location. | |
* | |
* @param $str The string you're searching for | |
* @param $arr A Drupal 8 Render array | |
* @return array Strings representing PHP array indices that contain your string within $arr | |
*/ | |
function find_str_in_render_arr($str, $arr){ | |
$ret = array(); | |
foreach($arr as $key => $val){ | |
if(is_string($key)){ | |
$left = "['"; | |
$right = "']"; | |
} | |
else{ | |
$left = "["; | |
$right = "]"; | |
} | |
if(is_array($val)){ | |
$recur = find_str_in_render_arr($str, $val); | |
foreach($recur as $found_str_keys){ | |
$ret[] = $left . $key . $right . $found_str_keys; | |
} | |
} | |
else if($str === $val || | |
($val instanceof Drupal\Core\StringTranslation\TranslatableMarkup && | |
$str == $val->render())){ | |
$ret[] = $left . $key . $right; | |
} | |
} | |
return $ret; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment