[NFC] Remove some more of the old cvs blocks
[civicrm-core.git] / Civi / Api4 / Utils / ArrayInsertionUtil.php
CommitLineData
19b53e5b
C
1<?php
2
380f3545
TO
3/*
4 +--------------------------------------------------------------------+
41498ac5 5 | Copyright CiviCRM LLC. All rights reserved. |
380f3545 6 | |
41498ac5
TO
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 |
380f3545
TO
10 +--------------------------------------------------------------------+
11 */
12
016d95d3 13namespace Civi\Api4\Utils;
14
380f3545 15/**
016d95d3 16 * Class ArrayInsertionUtil
380f3545 17 *
016d95d3 18 * @package Civi\Api4\Utils
380f3545 19 */
19b53e5b
C
20class ArrayInsertionUtil {
21
22 /**
23 * If the values to be inserted contain a key _parent_id they will only be
24 * inserted if the parent node ID matches their ID
25 *
26 * @param $array
27 * The array to insert the value in
28 * @param array $parts
29 * Path to insertion point with structure:
30 * [[ name => is_multiple ], ..]
31 * @param mixed $values
32 * The value to be inserted
33 */
34 public static function insert(&$array, $parts, $values) {
35 $key = key($parts);
36 $isMulti = array_shift($parts);
37 if (!isset($array[$key])) {
38 $array[$key] = $isMulti ? [] : NULL;
39 }
40 if (empty($parts)) {
41 $values = self::filterValues($array, $isMulti, $values);
42 $array[$key] = $values;
43 }
44 else {
45 if ($isMulti) {
46 foreach ($array[$key] as &$subArray) {
47 self::insert($subArray, $parts, $values);
48 }
49 }
50 else {
51 self::insert($array[$key], $parts, $values);
52 }
53 }
54 }
55
56 /**
57 * @param $parentArray
58 * @param $isMulti
59 * @param $values
60 *
61 * @return array|mixed
62 */
63 private static function filterValues($parentArray, $isMulti, $values) {
1b8e3bc8 64 $parentID = $parentArray['id'] ?? NULL;
19b53e5b
C
65
66 if ($parentID) {
67 $values = array_filter($values, function ($value) use ($parentID) {
1b8e3bc8 68 return ($value['_parent_id'] ?? NULL) == $parentID;
19b53e5b
C
69 });
70 }
71
72 $unsets = ['_parent_id', '_base_id'];
73 array_walk($values, function (&$value) use ($unsets) {
74 foreach ($unsets as $unset) {
75 if (isset($value[$unset])) {
76 unset($value[$unset]);
77 }
78 }
79 });
80
81 if (!$isMulti) {
82 $values = array_shift($values);
83 }
84 return $values;
85 }
86
87}