Merge pull request #16258 from samuelsov/i18ncountriesorder
[civicrm-core.git] / Civi / Api4 / Utils / ArrayInsertionUtil.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 * $Id$
18 *
19 */
20
21
22 namespace Civi\Api4\Utils;
23
24 use CRM_Utils_Array as UtilsArray;
25
26 class ArrayInsertionUtil {
27
28 /**
29 * If the values to be inserted contain a key _parent_id they will only be
30 * inserted if the parent node ID matches their ID
31 *
32 * @param $array
33 * The array to insert the value in
34 * @param array $parts
35 * Path to insertion point with structure:
36 * [[ name => is_multiple ], ..]
37 * @param mixed $values
38 * The value to be inserted
39 */
40 public static function insert(&$array, $parts, $values) {
41 $key = key($parts);
42 $isMulti = array_shift($parts);
43 if (!isset($array[$key])) {
44 $array[$key] = $isMulti ? [] : NULL;
45 }
46 if (empty($parts)) {
47 $values = self::filterValues($array, $isMulti, $values);
48 $array[$key] = $values;
49 }
50 else {
51 if ($isMulti) {
52 foreach ($array[$key] as &$subArray) {
53 self::insert($subArray, $parts, $values);
54 }
55 }
56 else {
57 self::insert($array[$key], $parts, $values);
58 }
59 }
60 }
61
62 /**
63 * @param $parentArray
64 * @param $isMulti
65 * @param $values
66 *
67 * @return array|mixed
68 */
69 private static function filterValues($parentArray, $isMulti, $values) {
70 $parentID = UtilsArray::value('id', $parentArray);
71
72 if ($parentID) {
73 $values = array_filter($values, function ($value) use ($parentID) {
74 return UtilsArray::value('_parent_id', $value) == $parentID;
75 });
76 }
77
78 $unsets = ['_parent_id', '_base_id'];
79 array_walk($values, function (&$value) use ($unsets) {
80 foreach ($unsets as $unset) {
81 if (isset($value[$unset])) {
82 unset($value[$unset]);
83 }
84 }
85 });
86
87 if (!$isMulti) {
88 $values = array_shift($values);
89 }
90 return $values;
91 }
92
93 }