5 * Contains Drupal\Console\Core\NestedArray.
8 namespace Drupal\Console\Core\Utils;
13 * @package Drupal\Console\Core\Utils
18 * Based on drupal class Drupal\Component\Utility\NestedArray
20 * Retrieves a value from a nested array with variable depth.
22 * This helper function should be used when the depth of the array element
23 * being retrieved may vary (that is, the number of parent keys is variable).
24 * It is primarily used for form structures and renderable arrays.
26 * Without this helper function the only way to get a nested array value with
27 * variable depth in one line would be using eval(), which should be avoided:
30 * // Do not do this! Avoid eval().
31 * // May also throw a PHP notice, if the variable array keys do not exist.
32 * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
35 * Instead, use this helper function:
37 * $value = NestedArray::getValue($form, $parents);
40 * A return value of NULL is ambiguous, and can mean either that the requested
41 * key does not exist, or that the actual value is NULL. If it is required to
42 * know whether the nested array key actually exists, pass a third argument
43 * that is altered by reference:
46 * $value = NestedArray::getValue($form, $parents, $key_exists);
48 * // Do something with $value.
52 * However if the number of array parent keys is static, the value should
53 * always be retrieved directly rather than calling this function.
56 * $value = $form['signature_settings']['signature'];
60 * The array from which to get the value.
61 * @param array $parents
62 * An array of parent keys of the value, starting with the outermost key.
63 * @param bool $key_exists
64 * (optional) If given, an already defined variable that is altered by
68 * The requested nested value. Possibly NULL if the value is NULL or not all
69 * nested parent keys exist. $key_exists is altered by reference and is a
70 * Boolean that indicates whether all nested parent keys exist (TRUE) or not
71 * (FALSE). This allows to distinguish between the two possibilities when
74 * @see NestedArray::setValue()
75 * @see NestedArray::unsetValue()
77 public static function &getValue(array &$array, array $parents, &$key_exists = null)
80 foreach ($parents as $parent) {
81 if (is_array($ref) && array_key_exists($parent, $ref)) {
82 $ref = &$ref[$parent];
94 * Sets a value in a nested array with variable depth.
96 * This helper function should be used when the depth of the array element you
97 * are changing may vary (that is, the number of parent keys is variable). It
98 * is primarily used for form structures and renderable arrays.
103 * // Assume you have a 'signature' element somewhere in a form. It might be:
104 * $form['signature_settings']['signature'] = array(
105 * '#type' => 'text_format',
106 * '#title' => t('Signature'),
108 * // Or, it might be further nested:
109 * $form['signature_settings']['user']['signature'] = array(
110 * '#type' => 'text_format',
111 * '#title' => t('Signature'),
115 * To deal with the situation, the code needs to figure out the route to the
116 * element, given an array of parents that is either
117 * @code array('signature_settings', 'signature') @endcode
118 * in the first case or
119 * @code array('signature_settings', 'user', 'signature') @endcode
120 * in the second case.
122 * Without this helper function the only way to set the signature element in
123 * one line would be using eval(), which should be avoided:
125 * // Do not do this! Avoid eval().
126 * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
129 * Instead, use this helper function:
131 * NestedArray::setValue($form, $parents, $element);
134 * However if the number of array parent keys is static, the value should
135 * always be set directly rather than calling this function. For instance,
136 * for the first example we could just do:
138 * $form['signature_settings']['signature'] = $element;
141 * @param array $array
142 * A reference to the array to modify.
143 * @param array $parents
144 * An array of parent keys, starting with the outermost key.
145 * @param mixed $value
148 * (optional) If TRUE, the value is forced into the structure even if it
149 * requires the deletion of an already existing non-array parent value. If
150 * FALSE, PHP throws an error if trying to add into a value that is not an
151 * array. Defaults to FALSE.
153 * @see NestedArray::unsetValue()
154 * @see NestedArray::getValue()
156 public static function setValue(array &$array, array $parents, $value, $force = false)
159 foreach ($parents as $parent) {
160 // PHP auto-creates container arrays and NULL entries without error if $ref
161 // is NULL, but throws an error if $ref is set, but not an array.
162 if ($force && isset($ref) && !is_array($ref)) {
165 $ref = &$ref[$parent];
171 * Replace a YAML key maintaining values
173 * @param array $array
174 * @param array $parents
177 public static function replaceKey(array &$array, array $parents, $new_key)
180 foreach ($parents as $parent) {
183 $ref = &$ref[$parent];
186 $father[$new_key] = $father[$key];
187 unset($father[$key]);
193 * @param bool $negate if Negate is true only if values are equal are returned.
194 * @param$$statistics mixed array
197 public function arrayDiff($array1, $array2, $negate = false, &$statistics)
200 foreach ($array1 as $key => $val) {
201 if (isset($array2[$key])) {
202 if (is_array($val) && $array2[$key]) {
203 $result[$key] = $this->arrayDiff($val, $array2[$key], $negate, $statistics);
204 if (empty($result[$key])) {
205 unset($result[$key]);
208 $statistics['total'] += 1;
209 if ($val == $array2[$key] && $negate) {
210 $result[$key] = $array2[$key];
211 $statistics['equal'] += 1;
212 } elseif ($val != $array2[$key] && $negate) {
213 $statistics['diff'] += 1;
214 } elseif ($val != $array2[$key] && !$negate) {
215 $result[$key] = $array2[$key];
216 $statistics['diff'] += 1;
217 } elseif ($val == $array2[$key] && !$negate) {
218 $result[$key] = $array2[$key];
219 $statistics['equal'] += 1;
223 if (is_array($val)) {
224 $statistics['diff'] += count($val, COUNT_RECURSIVE);
225 $statistics['total'] += count($val, COUNT_RECURSIVE);
227 $statistics['diff'] +=1;
228 $statistics['total'] += 1;
239 * @param array $array
240 * @param array $flatten_array
241 * @param string $key_flatten
243 public function yamlFlattenArray(array &$array, &$flatten_array, &$key_flatten = '')
245 foreach ($array as $key => $value) {
246 if (!empty($key_flatten)) {
251 if (is_array($value)) {
252 $this->yamlFlattenArray($value, $flatten_array, $key_flatten);
254 if (!empty($value)) {
255 $flatten_array[$key_flatten] = $value;
256 $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
258 // Return to previous key
259 $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
264 // Start again with flatten key after recursive call
265 $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
269 * @param array $array
270 * @param array $split_array
271 * @param int $indent_level
272 * @param array $key_flatten
273 * @param int $key_level
274 * @param bool $exclude_parents_key
276 public function yamlSplitArray(array &$array, array &$split_array, $indent_level = '', &$key_flatten, &$key_level, $exclude_parents_key)
278 foreach ($array as $key => $value) {
279 if (!$exclude_parents_key && !empty($key_flatten)) {
283 if ($exclude_parents_key) {
286 $key_flatten .= $key;
289 if ($key_level == $indent_level) {
290 if (!empty($value)) {
291 $split_array[$key_flatten] = $value;
293 if (!$exclude_parents_key) {
294 $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
298 if (is_array($value)) {
300 $this->yamlSplitArray($value, $split_array, $indent_level, $key_flatten, $key_level, $exclude_parents_key);
305 // Start again with flatten key after recursive call
306 if (!$exclude_parents_key) {
307 $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
313 * Unsets a value in a nested array with variable depth.
315 * This helper function should be used when the depth of the array element you
316 * are changing may vary (that is, the number of parent keys is variable). It
317 * is primarily used for form structures and renderable arrays.
322 * // Assume you have a 'signature' element somewhere in a form. It might be:
323 * $form['signature_settings']['signature'] = array(
324 * '#type' => 'text_format',
325 * '#title' => t('Signature'),
327 * // Or, it might be further nested:
328 * $form['signature_settings']['user']['signature'] = array(
329 * '#type' => 'text_format',
330 * '#title' => t('Signature'),
334 * To deal with the situation, the code needs to figure out the route to the
335 * element, given an array of parents that is either
336 * @code array('signature_settings', 'signature') @endcode
337 * in the first case or
338 * @code array('signature_settings', 'user', 'signature') @endcode
339 * in the second case.
341 * Without this helper function the only way to unset the signature element in
342 * one line would be using eval(), which should be avoided:
344 * // Do not do this! Avoid eval().
345 * eval('unset($form[\'' . implode("']['", $parents) . '\']);');
348 * Instead, use this helper function:
350 * NestedArray::unset_nested_value($form, $parents, $element);
353 * However if the number of array parent keys is static, the value should
354 * always be set directly rather than calling this function. For instance, for
355 * the first example we could just do:
357 * unset($form['signature_settings']['signature']);
360 * @param array $array
361 * A reference to the array to modify.
362 * @param array $parents
363 * An array of parent keys, starting with the outermost key and including
364 * the key to be unset.
365 * @param bool $key_existed
366 * (optional) If given, an already defined variable that is altered by
369 * @see NestedArray::setValue()
370 * @see NestedArray::getValue()
372 public static function unsetValue(array &$array, array $parents, &$key_existed = null)
374 $unset_key = array_pop($parents);
375 $ref = &self::getValue($array, $parents, $key_existed);
376 if ($key_existed && is_array($ref) && array_key_exists($unset_key, $ref)) {
378 unset($ref[$unset_key]);
380 $key_existed = false;
385 * Determines whether a nested array contains the requested keys.
387 * This helper function should be used when the depth of the array element to
388 * be checked may vary (that is, the number of parent keys is variable). See
389 * NestedArray::setValue() for details. It is primarily used for form
390 * structures and renderable arrays.
392 * If it is required to also get the value of the checked nested key, use
393 * NestedArray::getValue() instead.
395 * If the number of array parent keys is static, this helper function is
396 * unnecessary and the following code can be used instead:
399 * $value_exists = isset($form['signature_settings']['signature']);
400 * $key_exists = array_key_exists('signature', $form['signature_settings']);
403 * @param array $array
404 * The array with the value to check for.
405 * @param array $parents
406 * An array of parent keys of the value, starting with the outermost key.
409 * TRUE if all the parent keys exist, FALSE otherwise.
411 * @see NestedArray::getValue()
413 public static function keyExists(array $array, array $parents)
415 // Although this function is similar to PHP's array_key_exists(), its
416 // arguments should be consistent with getValue().
418 self::getValue($array, $parents, $key_exists);
423 * Merges multiple arrays, recursively, and returns the merged array.
425 * This function is similar to PHP's array_merge_recursive() function, but it
426 * handles non-array values differently. When merging values that are not both
427 * arrays, the latter value replaces the former rather than merging with it.
432 * $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
433 * $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
435 * // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
436 * $incorrect = array_merge_recursive($link_options_1, $link_options_2);
438 * // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
439 * $correct = NestedArray::mergeDeep($link_options_1, $link_options_2);
448 * @see NestedArray::mergeDeepArray()
450 public static function mergeDeep()
452 return self::mergeDeepArray(func_get_args());
456 * Merges multiple arrays, recursively, and returns the merged array.
458 * This function is equivalent to NestedArray::mergeDeep(), except the
459 * input arrays are passed as a single array parameter rather than a variable
462 * The following are equivalent:
463 * - NestedArray::mergeDeep($a, $b);
464 * - NestedArray::mergeDeepArray(array($a, $b));
466 * The following are also equivalent:
467 * - call_user_func_array('NestedArray::mergeDeep', $arrays_to_merge);
468 * - NestedArray::mergeDeepArray($arrays_to_merge);
470 * @param array $arrays
471 * An arrays of arrays to merge.
472 * @param bool $preserve_integer_keys
473 * (optional) If given, integer keys will be preserved and merged instead of
474 * appended. Defaults to FALSE.
479 * @see NestedArray::mergeDeep()
481 public static function mergeDeepArray(array $arrays, $preserve_integer_keys = false)
484 foreach ($arrays as $array) {
485 foreach ($array as $key => $value) {
486 // Renumber integer keys as array_merge_recursive() does unless
487 // $preserve_integer_keys is set to TRUE. Note that PHP automatically
488 // converts array keys that are integer strings (e.g., '1') to integers.
489 if (is_integer($key) && !$preserve_integer_keys) {
492 // Recurse when both values are arrays.
493 elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
494 $result[$key] = self::mergeDeepArray([$result[$key], $value], $preserve_integer_keys);
496 // Otherwise, use the latter value, overriding any previous value.
498 $result[$key] = $value;