Yaffs site version 1.1
[yaffs-website] / vendor / drupal / console-core / src / Utils / NestedArray.php
1 <?php
2
3 /**
4  * @file
5  * Contains Drupal\Console\Core\NestedArray.
6  */
7
8 namespace Drupal\Console\Core\Utils;
9
10 /**
11  * Class NestedArray
12  *
13  * @package Drupal\Console\Core\Utils
14  */
15 class NestedArray
16 {
17     /**
18      * Based on drupal class Drupal\Component\Utility\NestedArray
19      *
20      * Retrieves a value from a nested array with variable depth.
21      *
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.
25      *
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:
28      *
29      * @code
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) . "'];");
33      * @endcode
34      *
35      * Instead, use this helper function:
36      * @code
37      * $value = NestedArray::getValue($form, $parents);
38      * @endcode
39      *
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:
44      * @code
45      * $key_exists = NULL;
46      * $value = NestedArray::getValue($form, $parents, $key_exists);
47      * if ($key_exists) {
48      *   // Do something with $value.
49      * }
50      * @endcode
51      *
52      * However if the number of array parent keys is static, the value should
53      * always be retrieved directly rather than calling this function.
54      * For instance:
55      * @code
56      * $value = $form['signature_settings']['signature'];
57      * @endcode
58      *
59      * @param array $array
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
65      *   reference.
66      *
67      * @return mixed
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
72      *   NULL is returned.
73      *
74      * @see NestedArray::setValue()
75      * @see NestedArray::unsetValue()
76      */
77     public static function &getValue(array &$array, array $parents, &$key_exists = null)
78     {
79         $ref = &$array;
80         foreach ($parents as $parent) {
81             if (is_array($ref) && array_key_exists($parent, $ref)) {
82                 $ref = &$ref[$parent];
83             } else {
84                 $key_exists = false;
85                 $null = null;
86                 return $null;
87             }
88         }
89         $key_exists = true;
90         return $ref;
91     }
92
93     /**
94      * Sets a value in a nested array with variable depth.
95      *
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.
99      *
100      * Example:
101      *
102      * @code
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'),
107      * );
108      * // Or, it might be further nested:
109      * $form['signature_settings']['user']['signature'] = array(
110      *   '#type' => 'text_format',
111      *   '#title' => t('Signature'),
112      * );
113      * @endcode
114      *
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.
121      *
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:
124      * @code
125      * // Do not do this! Avoid eval().
126      * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
127      * @endcode
128      *
129      * Instead, use this helper function:
130      * @code
131      * NestedArray::setValue($form, $parents, $element);
132      * @endcode
133      *
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:
137      * @code
138      * $form['signature_settings']['signature'] = $element;
139      * @endcode
140      *
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
146      *   The value to set.
147      * @param bool  $force
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.
152      *
153      * @see NestedArray::unsetValue()
154      * @see NestedArray::getValue()
155      */
156     public static function setValue(array &$array, array $parents, $value, $force = false)
157     {
158         $ref = &$array;
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)) {
163                 $ref = [];
164             }
165             $ref = &$ref[$parent];
166         }
167         $ref = $value;
168     }
169
170     /**
171      * Replace a YAML key maintaining values
172      *
173      * @param array   $array
174      * @param array   $parents
175      * @param $new_key
176      */
177     public static function replaceKey(array &$array, array $parents, $new_key)
178     {
179         $ref = &$array;
180         foreach ($parents as $parent) {
181             $father = &$ref;
182             $key = $parent;
183             $ref = &$ref[$parent];
184         }
185
186         $father[$new_key] = $father[$key];
187         unset($father[$key]);
188     }
189
190     /**
191      * @param $array1
192      * @param $array2
193      * @param bool   $negate if Negate is true only if values are equal are returned.
194      * @param$$statistics mixed array
195      * @return array
196      */
197     public function arrayDiff($array1, $array2, $negate = false, &$statistics)
198     {
199         $result = [];
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]);
206                     }
207                 } else {
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;
220                     }
221                 }
222             } else {
223                 if (is_array($val)) {
224                     $statistics['diff'] += count($val, COUNT_RECURSIVE);
225                     $statistics['total'] += count($val, COUNT_RECURSIVE);
226                 } else {
227                     $statistics['diff'] +=1;
228                     $statistics['total'] += 1;
229                 }
230             }
231         }
232
233         return $result;
234     }
235
236     /**
237      * Flat a yaml file
238      *
239      * @param array  $array
240      * @param array  $flatten_array
241      * @param string $key_flatten
242      */
243     public function yamlFlattenArray(array &$array, &$flatten_array, &$key_flatten = '')
244     {
245         foreach ($array as $key => $value) {
246             if (!empty($key_flatten)) {
247                 $key_flatten.= '.';
248             }
249             $key_flatten.= $key;
250
251             if (is_array($value)) {
252                 $this->yamlFlattenArray($value, $flatten_array, $key_flatten);
253             } else {
254                 if (!empty($value)) {
255                     $flatten_array[$key_flatten] = $value;
256                     $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
257                 } else {
258                     // Return to previous key
259                     $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
260                 }
261             }
262         }
263
264         // Start again with flatten key after recursive call
265         $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
266     }
267
268     /**
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
275      */
276     public function yamlSplitArray(array &$array, array &$split_array, $indent_level = '', &$key_flatten, &$key_level, $exclude_parents_key)
277     {
278         foreach ($array as $key => $value) {
279             if (!$exclude_parents_key && !empty($key_flatten)) {
280                 $key_flatten.= '.';
281             }
282
283             if ($exclude_parents_key) {
284                 $key_flatten = $key;
285             } else {
286                 $key_flatten .= $key;
287             }
288
289             if ($key_level == $indent_level) {
290                 if (!empty($value)) {
291                     $split_array[$key_flatten] = $value;
292
293                     if (!$exclude_parents_key) {
294                         $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
295                     }
296                 }
297             } else {
298                 if (is_array($value)) {
299                     $key_level++;
300                     $this->yamlSplitArray($value, $split_array, $indent_level, $key_flatten, $key_level, $exclude_parents_key);
301                 }
302             }
303         }
304
305         // Start again with flatten key after recursive call
306         if (!$exclude_parents_key) {
307             $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
308         }
309
310         $key_level--;
311     }
312     /**
313      * Unsets a value in a nested array with variable depth.
314      *
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.
318      *
319      * Example:
320      *
321      * @code
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'),
326      * );
327      * // Or, it might be further nested:
328      * $form['signature_settings']['user']['signature'] = array(
329      *   '#type' => 'text_format',
330      *   '#title' => t('Signature'),
331      * );
332      * @endcode
333      *
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.
340      *
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:
343      * @code
344      * // Do not do this! Avoid eval().
345      * eval('unset($form[\'' . implode("']['", $parents) . '\']);');
346      * @endcode
347      *
348      * Instead, use this helper function:
349      * @code
350      * NestedArray::unset_nested_value($form, $parents, $element);
351      * @endcode
352      *
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:
356      * @code
357      * unset($form['signature_settings']['signature']);
358      * @endcode
359      *
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
367      *   reference.
368      *
369      * @see NestedArray::setValue()
370      * @see NestedArray::getValue()
371      */
372     public static function unsetValue(array &$array, array $parents, &$key_existed = null)
373     {
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)) {
377             $key_existed = true;
378             unset($ref[$unset_key]);
379         } else {
380             $key_existed = false;
381         }
382     }
383
384     /**
385      * Determines whether a nested array contains the requested keys.
386      *
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.
391      *
392      * If it is required to also get the value of the checked nested key, use
393      * NestedArray::getValue() instead.
394      *
395      * If the number of array parent keys is static, this helper function is
396      * unnecessary and the following code can be used instead:
397      *
398      * @code
399      * $value_exists = isset($form['signature_settings']['signature']);
400      * $key_exists = array_key_exists('signature', $form['signature_settings']);
401      * @endcode
402      *
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.
407      *
408      * @return bool
409      *   TRUE if all the parent keys exist, FALSE otherwise.
410      *
411      * @see NestedArray::getValue()
412      */
413     public static function keyExists(array $array, array $parents)
414     {
415         // Although this function is similar to PHP's array_key_exists(), its
416         // arguments should be consistent with getValue().
417         $key_exists = null;
418         self::getValue($array, $parents, $key_exists);
419         return $key_exists;
420     }
421
422     /**
423      * Merges multiple arrays, recursively, and returns the merged array.
424      *
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.
428      *
429      * Example:
430      *
431      * @code
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')));
434      *
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);
437      *
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);
440      * @endcode
441      *
442      * @param array ...
443      *   Arrays to merge.
444      *
445      * @return array
446      *   The merged array.
447      *
448      * @see NestedArray::mergeDeepArray()
449      */
450     public static function mergeDeep()
451     {
452         return self::mergeDeepArray(func_get_args());
453     }
454
455     /**
456      * Merges multiple arrays, recursively, and returns the merged array.
457      *
458      * This function is equivalent to NestedArray::mergeDeep(), except the
459      * input arrays are passed as a single array parameter rather than a variable
460      * parameter list.
461      *
462      * The following are equivalent:
463      * - NestedArray::mergeDeep($a, $b);
464      * - NestedArray::mergeDeepArray(array($a, $b));
465      *
466      * The following are also equivalent:
467      * - call_user_func_array('NestedArray::mergeDeep', $arrays_to_merge);
468      * - NestedArray::mergeDeepArray($arrays_to_merge);
469      *
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.
475      *
476      * @return array
477      *   The merged array.
478      *
479      * @see NestedArray::mergeDeep()
480      */
481     public static function mergeDeepArray(array $arrays, $preserve_integer_keys = false)
482     {
483         $result = [];
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) {
490                     $result[] = $value;
491                 }
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);
495                 }
496                 // Otherwise, use the latter value, overriding any previous value.
497                 else {
498                     $result[$key] = $value;
499                 }
500             }
501         }
502         return $result;
503     }
504 }