NestedArray.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. <?php
  2. namespace Drupal\Component\Utility;
  3. /**
  4. * Provides helpers to perform operations on nested arrays and array keys of variable depth.
  5. *
  6. * @ingroup utility
  7. */
  8. class NestedArray {
  9. /**
  10. * Retrieves a value from a nested array with variable depth.
  11. *
  12. * This helper function should be used when the depth of the array element
  13. * being retrieved may vary (that is, the number of parent keys is variable).
  14. * It is primarily used for form structures and renderable arrays.
  15. *
  16. * Without this helper function the only way to get a nested array value with
  17. * variable depth in one line would be using eval(), which should be avoided:
  18. * @code
  19. * // Do not do this! Avoid eval().
  20. * // May also throw a PHP notice, if the variable array keys do not exist.
  21. * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
  22. * @endcode
  23. *
  24. * Instead, use this helper function:
  25. * @code
  26. * $value = NestedArray::getValue($form, $parents);
  27. * @endcode
  28. *
  29. * A return value of NULL is ambiguous, and can mean either that the requested
  30. * key does not exist, or that the actual value is NULL. If it is required to
  31. * know whether the nested array key actually exists, pass a third argument
  32. * that is altered by reference:
  33. * @code
  34. * $key_exists = NULL;
  35. * $value = NestedArray::getValue($form, $parents, $key_exists);
  36. * if ($key_exists) {
  37. * // Do something with $value.
  38. * }
  39. * @endcode
  40. *
  41. * However if the number of array parent keys is static, the value should
  42. * always be retrieved directly rather than calling this function.
  43. * For instance:
  44. * @code
  45. * $value = $form['signature_settings']['signature'];
  46. * @endcode
  47. *
  48. * @param array $array
  49. * The array from which to get the value.
  50. * @param array $parents
  51. * An array of parent keys of the value, starting with the outermost key.
  52. * @param bool $key_exists
  53. * (optional) If given, an already defined variable that is altered by
  54. * reference.
  55. *
  56. * @return mixed
  57. * The requested nested value. Possibly NULL if the value is NULL or not all
  58. * nested parent keys exist. $key_exists is altered by reference and is a
  59. * Boolean that indicates whether all nested parent keys exist (TRUE) or not
  60. * (FALSE). This allows to distinguish between the two possibilities when
  61. * NULL is returned.
  62. *
  63. * @see NestedArray::setValue()
  64. * @see NestedArray::unsetValue()
  65. */
  66. public static function &getValue(array &$array, array $parents, &$key_exists = NULL) {
  67. $ref = &$array;
  68. foreach ($parents as $parent) {
  69. if (is_array($ref) && (isset($ref[$parent]) || array_key_exists($parent, $ref))) {
  70. $ref = &$ref[$parent];
  71. }
  72. else {
  73. $key_exists = FALSE;
  74. $null = NULL;
  75. return $null;
  76. }
  77. }
  78. $key_exists = TRUE;
  79. return $ref;
  80. }
  81. /**
  82. * Sets a value in a nested array with variable depth.
  83. *
  84. * This helper function should be used when the depth of the array element you
  85. * are changing may vary (that is, the number of parent keys is variable). It
  86. * is primarily used for form structures and renderable arrays.
  87. *
  88. * Example:
  89. * @code
  90. * // Assume you have a 'signature' element somewhere in a form. It might be:
  91. * $form['signature_settings']['signature'] = array(
  92. * '#type' => 'text_format',
  93. * '#title' => t('Signature'),
  94. * );
  95. * // Or, it might be further nested:
  96. * $form['signature_settings']['user']['signature'] = array(
  97. * '#type' => 'text_format',
  98. * '#title' => t('Signature'),
  99. * );
  100. * @endcode
  101. *
  102. * To deal with the situation, the code needs to figure out the route to the
  103. * element, given an array of parents that is either
  104. * @code array('signature_settings', 'signature') @endcode
  105. * in the first case or
  106. * @code array('signature_settings', 'user', 'signature') @endcode
  107. * in the second case.
  108. *
  109. * Without this helper function the only way to set the signature element in
  110. * one line would be using eval(), which should be avoided:
  111. * @code
  112. * // Do not do this! Avoid eval().
  113. * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
  114. * @endcode
  115. *
  116. * Instead, use this helper function:
  117. * @code
  118. * NestedArray::setValue($form, $parents, $element);
  119. * @endcode
  120. *
  121. * However if the number of array parent keys is static, the value should
  122. * always be set directly rather than calling this function. For instance,
  123. * for the first example we could just do:
  124. * @code
  125. * $form['signature_settings']['signature'] = $element;
  126. * @endcode
  127. *
  128. * @param array $array
  129. * A reference to the array to modify.
  130. * @param array $parents
  131. * An array of parent keys, starting with the outermost key.
  132. * @param mixed $value
  133. * The value to set.
  134. * @param bool $force
  135. * (optional) If TRUE, the value is forced into the structure even if it
  136. * requires the deletion of an already existing non-array parent value. If
  137. * FALSE, PHP throws an error if trying to add into a value that is not an
  138. * array. Defaults to FALSE.
  139. *
  140. * @see NestedArray::unsetValue()
  141. * @see NestedArray::getValue()
  142. */
  143. public static function setValue(array &$array, array $parents, $value, $force = FALSE) {
  144. $ref = &$array;
  145. foreach ($parents as $parent) {
  146. // PHP auto-creates container arrays and NULL entries without error if $ref
  147. // is NULL, but throws an error if $ref is set, but not an array.
  148. if ($force && isset($ref) && !is_array($ref)) {
  149. $ref = [];
  150. }
  151. $ref = &$ref[$parent];
  152. }
  153. $ref = $value;
  154. }
  155. /**
  156. * Unsets a value in a nested array with variable depth.
  157. *
  158. * This helper function should be used when the depth of the array element you
  159. * are changing may vary (that is, the number of parent keys is variable). It
  160. * is primarily used for form structures and renderable arrays.
  161. *
  162. * Example:
  163. * @code
  164. * // Assume you have a 'signature' element somewhere in a form. It might be:
  165. * $form['signature_settings']['signature'] = array(
  166. * '#type' => 'text_format',
  167. * '#title' => t('Signature'),
  168. * );
  169. * // Or, it might be further nested:
  170. * $form['signature_settings']['user']['signature'] = array(
  171. * '#type' => 'text_format',
  172. * '#title' => t('Signature'),
  173. * );
  174. * @endcode
  175. *
  176. * To deal with the situation, the code needs to figure out the route to the
  177. * element, given an array of parents that is either
  178. * @code array('signature_settings', 'signature') @endcode
  179. * in the first case or
  180. * @code array('signature_settings', 'user', 'signature') @endcode
  181. * in the second case.
  182. *
  183. * Without this helper function the only way to unset the signature element in
  184. * one line would be using eval(), which should be avoided:
  185. * @code
  186. * // Do not do this! Avoid eval().
  187. * eval('unset($form[\'' . implode("']['", $parents) . '\']);');
  188. * @endcode
  189. *
  190. * Instead, use this helper function:
  191. * @code
  192. * NestedArray::unset_nested_value($form, $parents, $element);
  193. * @endcode
  194. *
  195. * However if the number of array parent keys is static, the value should
  196. * always be set directly rather than calling this function. For instance, for
  197. * the first example we could just do:
  198. * @code
  199. * unset($form['signature_settings']['signature']);
  200. * @endcode
  201. *
  202. * @param array $array
  203. * A reference to the array to modify.
  204. * @param array $parents
  205. * An array of parent keys, starting with the outermost key and including
  206. * the key to be unset.
  207. * @param bool $key_existed
  208. * (optional) If given, an already defined variable that is altered by
  209. * reference.
  210. *
  211. * @see NestedArray::setValue()
  212. * @see NestedArray::getValue()
  213. */
  214. public static function unsetValue(array &$array, array $parents, &$key_existed = NULL) {
  215. $unset_key = array_pop($parents);
  216. $ref = &self::getValue($array, $parents, $key_existed);
  217. if ($key_existed && is_array($ref) && (isset($ref[$unset_key]) || array_key_exists($unset_key, $ref))) {
  218. $key_existed = TRUE;
  219. unset($ref[$unset_key]);
  220. }
  221. else {
  222. $key_existed = FALSE;
  223. }
  224. }
  225. /**
  226. * Determines whether a nested array contains the requested keys.
  227. *
  228. * This helper function should be used when the depth of the array element to
  229. * be checked may vary (that is, the number of parent keys is variable). See
  230. * NestedArray::setValue() for details. It is primarily used for form
  231. * structures and renderable arrays.
  232. *
  233. * If it is required to also get the value of the checked nested key, use
  234. * NestedArray::getValue() instead.
  235. *
  236. * If the number of array parent keys is static, this helper function is
  237. * unnecessary and the following code can be used instead:
  238. * @code
  239. * $value_exists = isset($form['signature_settings']['signature']);
  240. * $key_exists = array_key_exists('signature', $form['signature_settings']);
  241. * @endcode
  242. *
  243. * @param array $array
  244. * The array with the value to check for.
  245. * @param array $parents
  246. * An array of parent keys of the value, starting with the outermost key.
  247. *
  248. * @return bool
  249. * TRUE if all the parent keys exist, FALSE otherwise.
  250. *
  251. * @see NestedArray::getValue()
  252. */
  253. public static function keyExists(array $array, array $parents) {
  254. // Although this function is similar to PHP's array_key_exists(), its
  255. // arguments should be consistent with getValue().
  256. $key_exists = NULL;
  257. self::getValue($array, $parents, $key_exists);
  258. return $key_exists;
  259. }
  260. /**
  261. * Merges multiple arrays, recursively, and returns the merged array.
  262. *
  263. * This function is similar to PHP's array_merge_recursive() function, but it
  264. * handles non-array values differently. When merging values that are not both
  265. * arrays, the latter value replaces the former rather than merging with it.
  266. *
  267. * Example:
  268. * @code
  269. * $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
  270. * $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
  271. *
  272. * // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
  273. * $incorrect = array_merge_recursive($link_options_1, $link_options_2);
  274. *
  275. * // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
  276. * $correct = NestedArray::mergeDeep($link_options_1, $link_options_2);
  277. * @endcode
  278. *
  279. * @param array ...
  280. * Arrays to merge.
  281. *
  282. * @return array
  283. * The merged array.
  284. *
  285. * @see NestedArray::mergeDeepArray()
  286. */
  287. public static function mergeDeep() {
  288. return self::mergeDeepArray(func_get_args());
  289. }
  290. /**
  291. * Merges multiple arrays, recursively, and returns the merged array.
  292. *
  293. * This function is equivalent to NestedArray::mergeDeep(), except the
  294. * input arrays are passed as a single array parameter rather than a variable
  295. * parameter list.
  296. *
  297. * The following are equivalent:
  298. * - NestedArray::mergeDeep($a, $b);
  299. * - NestedArray::mergeDeepArray(array($a, $b));
  300. *
  301. * The following are also equivalent:
  302. * - call_user_func_array('NestedArray::mergeDeep', $arrays_to_merge);
  303. * - NestedArray::mergeDeepArray($arrays_to_merge);
  304. *
  305. * @param array $arrays
  306. * An arrays of arrays to merge.
  307. * @param bool $preserve_integer_keys
  308. * (optional) If given, integer keys will be preserved and merged instead of
  309. * appended. Defaults to FALSE.
  310. *
  311. * @return array
  312. * The merged array.
  313. *
  314. * @see NestedArray::mergeDeep()
  315. */
  316. public static function mergeDeepArray(array $arrays, $preserve_integer_keys = FALSE) {
  317. $result = [];
  318. foreach ($arrays as $array) {
  319. foreach ($array as $key => $value) {
  320. // Renumber integer keys as array_merge_recursive() does unless
  321. // $preserve_integer_keys is set to TRUE. Note that PHP automatically
  322. // converts array keys that are integer strings (e.g., '1') to integers.
  323. if (is_int($key) && !$preserve_integer_keys) {
  324. $result[] = $value;
  325. }
  326. // Recurse when both values are arrays.
  327. elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
  328. $result[$key] = self::mergeDeepArray([$result[$key], $value], $preserve_integer_keys);
  329. }
  330. // Otherwise, use the latter value, overriding any previous value.
  331. else {
  332. $result[$key] = $value;
  333. }
  334. }
  335. }
  336. return $result;
  337. }
  338. /**
  339. * Filters a nested array recursively.
  340. *
  341. * @param array $array
  342. * The filtered nested array.
  343. * @param callable|null $callable
  344. * The callable to apply for filtering.
  345. *
  346. * @return array
  347. * The filtered array.
  348. */
  349. public static function filter(array $array, callable $callable = NULL) {
  350. $array = is_callable($callable) ? array_filter($array, $callable) : array_filter($array);
  351. foreach ($array as &$element) {
  352. if (is_array($element)) {
  353. $element = static::filter($element, $callable);
  354. }
  355. }
  356. return $array;
  357. }
  358. }