NestedArray.php 13 KB

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