5904b8e1105ba068cfc4b62f82522ca9e6a7ebd5
[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  * @package Drupal\Console\Core\Utils
13  */
14 class NestedArray
15 {
16     /**
17      * Based on drupal class Drupal\Component\Utility\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      *
28      * @code
29      * // Do not do this! Avoid eval().
30      * // May also throw a PHP notice, if the variable array keys do not exist.
31      * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
32      * @endcode
33      *
34      * Instead, use this helper function:
35      * @code
36      * $value = NestedArray::getValue($form, $parents);
37      * @endcode
38      *
39      * A return value of NULL is ambiguous, and can mean either that the requested
40      * key does not exist, or that the actual value is NULL. If it is required to
41      * know whether the nested array key actually exists, pass a third argument
42      * that is altered by reference:
43      * @code
44      * $key_exists = NULL;
45      * $value = NestedArray::getValue($form, $parents, $key_exists);
46      * if ($key_exists) {
47      *   // Do something with $value.
48      * }
49      * @endcode
50      *
51      * However if the number of array parent keys is static, the value should
52      * always be retrieved directly rather than calling this function.
53      * For instance:
54      * @code
55      * $value = $form['signature_settings']['signature'];
56      * @endcode
57      *
58      * @param array $array
59      *   The array from which to get the value.
60      * @param array $parents
61      *   An array of parent keys of the value, starting with the outermost key.
62      * @param bool  $key_exists
63      *   (optional) If given, an already defined variable that is altered by
64      *   reference.
65      *
66      * @return mixed
67      *   The requested nested value. Possibly NULL if the value is NULL or not all
68      *   nested parent keys exist. $key_exists is altered by reference and is a
69      *   Boolean that indicates whether all nested parent keys exist (TRUE) or not
70      *   (FALSE). This allows to distinguish between the two possibilities when
71      *   NULL is returned.
72      *
73      * @see NestedArray::setValue()
74      * @see NestedArray::unsetValue()
75      */
76     public static function &getValue(array &$array, array $parents, &$key_exists = null)
77     {
78         $ref = &$array;
79         foreach ($parents as $parent) {
80             if (is_array($ref) && array_key_exists($parent, $ref)) {
81                 $ref = &$ref[$parent];
82             } else {
83                 $key_exists = false;
84                 $null = null;
85                 return $null;
86             }
87         }
88         $key_exists = true;
89         return $ref;
90     }
91
92     /**
93      * Sets a value in a nested array with variable depth.
94      *
95      * This helper function should be used when the depth of the array element you
96      * are changing may vary (that is, the number of parent keys is variable). It
97      * is primarily used for form structures and renderable arrays.
98      *
99      * Example:
100      *
101      * @code
102      * // Assume you have a 'signature' element somewhere in a form. It might be:
103      * $form['signature_settings']['signature'] = array(
104      *   '#type' => 'text_format',
105      *   '#title' => t('Signature'),
106      * );
107      * // Or, it might be further nested:
108      * $form['signature_settings']['user']['signature'] = array(
109      *   '#type' => 'text_format',
110      *   '#title' => t('Signature'),
111      * );
112      * @endcode
113      *
114      * To deal with the situation, the code needs to figure out the route to the
115      * element, given an array of parents that is either
116      * @code    array('signature_settings', 'signature') @endcode
117      * in the first case or
118      * @code    array('signature_settings', 'user', 'signature') @endcode
119      * in the second case.
120      *
121      * Without this helper function the only way to set the signature element in
122      * one line would be using eval(), which should be avoided:
123      * @code
124      * // Do not do this! Avoid eval().
125      * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
126      * @endcode
127      *
128      * Instead, use this helper function:
129      * @code
130      * NestedArray::setValue($form, $parents, $element);
131      * @endcode
132      *
133      * However if the number of array parent keys is static, the value should
134      * always be set directly rather than calling this function. For instance,
135      * for the first example we could just do:
136      * @code
137      * $form['signature_settings']['signature'] = $element;
138      * @endcode
139      *
140      * @param array $array
141      *   A reference to the array to modify.
142      * @param array $parents
143      *   An array of parent keys, starting with the outermost key.
144      * @param mixed $value
145      *   The value to set.
146      * @param bool  $force
147      *   (optional) If TRUE, the value is forced into the structure even if it
148      *   requires the deletion of an already existing non-array parent value. If
149      *   FALSE, PHP throws an error if trying to add into a value that is not an
150      *   array. Defaults to FALSE.
151      *
152      * @see NestedArray::unsetValue()
153      * @see NestedArray::getValue()
154      */
155     public static function setValue(array &$array, array $parents, $value, $force = false)
156     {
157         $ref = &$array;
158         foreach ($parents as $parent) {
159             // PHP auto-creates container arrays and NULL entries without error if $ref
160             // is NULL, but throws an error if $ref is set, but not an array.
161             if ($force && isset($ref) && !is_array($ref)) {
162                 $ref = array();
163             }
164             $ref = &$ref[$parent];
165         }
166         $ref = $value;
167     }
168
169     /**
170      * Replace a YAML key maintaining values
171      * @param array   $array
172      * @param array   $parents
173      * @param $new_key
174      */
175     public static function replaceKey(array &$array, array $parents, $new_key)
176     {
177         $ref = &$array;
178         foreach ($parents as $parent) {
179             $father = &$ref;
180             $key = $parent;
181             $ref = &$ref[$parent];
182         }
183
184         $father[$new_key] = $father[$key];
185         unset($father[$key]);
186     }
187
188     /**
189      * @param $array1
190      * @param $array2
191      * @param bool   $negate if Negate is true only if values are equal are returned.
192      * @param$$statistics mixed array
193      * @return array
194      */
195     public function arrayDiff($array1, $array2, $negate = false, &$statistics)
196     {
197         $result = array();
198         foreach ($array1 as $key => $val) {
199             if (isset($array2[$key])) {
200                 if (is_array($val) && $array2[$key]) {
201                     $result[$key] = $this->arrayDiff($val, $array2[$key], $negate, $statistics);
202                     if (empty($result[$key])) {
203                         unset($result[$key]);
204                     }
205                 } else {
206                     $statistics['total'] += 1;
207                     if ($val == $array2[$key] && $negate) {
208                         $result[$key] = $array2[$key];
209                         $statistics['equal'] += 1;
210                     } elseif ($val != $array2[$key] && $negate) {
211                         $statistics['diff'] += 1;
212                     } elseif ($val != $array2[$key] && !$negate) {
213                         $result[$key] = $array2[$key];
214                         $statistics['diff'] += 1;
215                     } elseif ($val == $array2[$key] && !$negate) {
216                         $result[$key] = $array2[$key];
217                         $statistics['equal'] += 1;
218                     }
219                 }
220             } else {
221                 if (is_array($val)) {
222                     $statistics['diff'] += count($val, COUNT_RECURSIVE);
223                     $statistics['total'] += count($val, COUNT_RECURSIVE);
224                 } else {
225                     $statistics['diff'] +=1;
226                     $statistics['total'] += 1;
227                 }
228             }
229         }
230
231         return $result;
232     }
233
234     /**
235      * Flat a yaml file
236      * @param array  $array
237      * @param array  $flatten_array
238      * @param string $key_flatten
239      */
240     public function yamlFlattenArray(array &$array, &$flatten_array, &$key_flatten = '')
241     {
242         foreach ($array as $key => $value) {
243             if (!empty($key_flatten)) {
244                 $key_flatten.= '.';
245             }
246             $key_flatten.= $key;
247
248             if (is_array($value)) {
249                 $this->yamlFlattenArray($value, $flatten_array, $key_flatten);
250             } else {
251                 if (!empty($value)) {
252                     $flatten_array[$key_flatten] = $value;
253                     $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
254                 } else {
255                     // Return to previous key
256                     $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
257                 }
258             }
259         }
260
261         // Start again with flatten key after recursive call
262         $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
263     }
264
265     /**
266      * @param array $array
267      * @param array $split_array
268      * @param int   $indent_level
269      * @param array $key_flatten
270      * @param int   $key_level
271      * @param bool  $exclude_parents_key
272      */
273     public function yamlSplitArray(array &$array, array &$split_array, $indent_level = '', &$key_flatten, &$key_level, $exclude_parents_key)
274     {
275         foreach ($array as $key => $value) {
276             if (!$exclude_parents_key && !empty($key_flatten)) {
277                 $key_flatten.= '.';
278             }
279
280             if ($exclude_parents_key) {
281                 $key_flatten = $key;
282             } else {
283                 $key_flatten .= $key;
284             }
285
286             if ($key_level == $indent_level) {
287                 if (!empty($value)) {
288                     $split_array[$key_flatten] = $value;
289
290                     if (!$exclude_parents_key) {
291                         $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
292                     }
293                 }
294             } else {
295                 if (is_array($value)) {
296                     $key_level++;
297                     $this->yamlSplitArray($value, $split_array, $indent_level, $key_flatten, $key_level, $exclude_parents_key);
298                 }
299             }
300         }
301
302         // Start again with flatten key after recursive call
303         if (!$exclude_parents_key) {
304             $key_flatten = substr($key_flatten, 0, strrpos($key_flatten, "."));
305         }
306
307         $key_level--;
308     }
309     /**
310      * Unsets a value in a nested array with variable depth.
311      *
312      * This helper function should be used when the depth of the array element you
313      * are changing may vary (that is, the number of parent keys is variable). It
314      * is primarily used for form structures and renderable arrays.
315      *
316      * Example:
317      *
318      * @code
319      * // Assume you have a 'signature' element somewhere in a form. It might be:
320      * $form['signature_settings']['signature'] = array(
321      *   '#type' => 'text_format',
322      *   '#title' => t('Signature'),
323      * );
324      * // Or, it might be further nested:
325      * $form['signature_settings']['user']['signature'] = array(
326      *   '#type' => 'text_format',
327      *   '#title' => t('Signature'),
328      * );
329      * @endcode
330      *
331      * To deal with the situation, the code needs to figure out the route to the
332      * element, given an array of parents that is either
333      * @code    array('signature_settings', 'signature') @endcode
334      * in the first case or
335      * @code    array('signature_settings', 'user', 'signature') @endcode
336      * in the second case.
337      *
338      * Without this helper function the only way to unset the signature element in
339      * one line would be using eval(), which should be avoided:
340      * @code
341      * // Do not do this! Avoid eval().
342      * eval('unset($form[\'' . implode("']['", $parents) . '\']);');
343      * @endcode
344      *
345      * Instead, use this helper function:
346      * @code
347      * NestedArray::unset_nested_value($form, $parents, $element);
348      * @endcode
349      *
350      * However if the number of array parent keys is static, the value should
351      * always be set directly rather than calling this function. For instance, for
352      * the first example we could just do:
353      * @code
354      * unset($form['signature_settings']['signature']);
355      * @endcode
356      *
357      * @param array $array
358      *   A reference to the array to modify.
359      * @param array $parents
360      *   An array of parent keys, starting with the outermost key and including
361      *   the key to be unset.
362      * @param bool  $key_existed
363      *   (optional) If given, an already defined variable that is altered by
364      *   reference.
365      *
366      * @see NestedArray::setValue()
367      * @see NestedArray::getValue()
368      */
369     public static function unsetValue(array &$array, array $parents, &$key_existed = null)
370     {
371         $unset_key = array_pop($parents);
372         $ref = &self::getValue($array, $parents, $key_existed);
373         if ($key_existed && is_array($ref) && array_key_exists($unset_key, $ref)) {
374             $key_existed = true;
375             unset($ref[$unset_key]);
376         } else {
377             $key_existed = false;
378         }
379     }
380
381     /**
382      * Determines whether a nested array contains the requested keys.
383      *
384      * This helper function should be used when the depth of the array element to
385      * be checked may vary (that is, the number of parent keys is variable). See
386      * NestedArray::setValue() for details. It is primarily used for form
387      * structures and renderable arrays.
388      *
389      * If it is required to also get the value of the checked nested key, use
390      * NestedArray::getValue() instead.
391      *
392      * If the number of array parent keys is static, this helper function is
393      * unnecessary and the following code can be used instead:
394      *
395      * @code
396      * $value_exists = isset($form['signature_settings']['signature']);
397      * $key_exists = array_key_exists('signature', $form['signature_settings']);
398      * @endcode
399      *
400      * @param array $array
401      *   The array with the value to check for.
402      * @param array $parents
403      *   An array of parent keys of the value, starting with the outermost key.
404      *
405      * @return bool
406      *   TRUE if all the parent keys exist, FALSE otherwise.
407      *
408      * @see NestedArray::getValue()
409      */
410     public static function keyExists(array $array, array $parents)
411     {
412         // Although this function is similar to PHP's array_key_exists(), its
413         // arguments should be consistent with getValue().
414         $key_exists = null;
415         self::getValue($array, $parents, $key_exists);
416         return $key_exists;
417     }
418
419     /**
420      * Merges multiple arrays, recursively, and returns the merged array.
421      *
422      * This function is similar to PHP's array_merge_recursive() function, but it
423      * handles non-array values differently. When merging values that are not both
424      * arrays, the latter value replaces the former rather than merging with it.
425      *
426      * Example:
427      *
428      * @code
429      * $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
430      * $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
431      *
432      * // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
433      * $incorrect = array_merge_recursive($link_options_1, $link_options_2);
434      *
435      * // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
436      * $correct = NestedArray::mergeDeep($link_options_1, $link_options_2);
437      * @endcode
438      *
439      * @param array ...
440      *   Arrays to merge.
441      *
442      * @return array
443      *   The merged array.
444      *
445      * @see NestedArray::mergeDeepArray()
446      */
447     public static function mergeDeep()
448     {
449         return self::mergeDeepArray(func_get_args());
450     }
451
452     /**
453      * Merges multiple arrays, recursively, and returns the merged array.
454      *
455      * This function is equivalent to NestedArray::mergeDeep(), except the
456      * input arrays are passed as a single array parameter rather than a variable
457      * parameter list.
458      *
459      * The following are equivalent:
460      * - NestedArray::mergeDeep($a, $b);
461      * - NestedArray::mergeDeepArray(array($a, $b));
462      *
463      * The following are also equivalent:
464      * - call_user_func_array('NestedArray::mergeDeep', $arrays_to_merge);
465      * - NestedArray::mergeDeepArray($arrays_to_merge);
466      *
467      * @param array $arrays
468      *   An arrays of arrays to merge.
469      * @param bool  $preserve_integer_keys
470      *   (optional) If given, integer keys will be preserved and merged instead of
471      *   appended. Defaults to FALSE.
472      *
473      * @return array
474      *   The merged array.
475      *
476      * @see NestedArray::mergeDeep()
477      */
478     public static function mergeDeepArray(array $arrays, $preserve_integer_keys = false)
479     {
480         $result = array();
481         foreach ($arrays as $array) {
482             foreach ($array as $key => $value) {
483                 // Renumber integer keys as array_merge_recursive() does unless
484                 // $preserve_integer_keys is set to TRUE. Note that PHP automatically
485                 // converts array keys that are integer strings (e.g., '1') to integers.
486                 if (is_integer($key) && !$preserve_integer_keys) {
487                     $result[] = $value;
488                 }
489                 // Recurse when both values are arrays.
490                 elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
491                     $result[$key] = self::mergeDeepArray(array($result[$key], $value), $preserve_integer_keys);
492                 }
493                 // Otherwise, use the latter value, overriding any previous value.
494                 else {
495                     $result[$key] = $value;
496                 }
497             }
498         }
499         return $result;
500     }
501 }