Merge pull request #16441 from eileenmcnaughton/event_pre
[civicrm-core.git] / Civi / Api4 / Generic / BasicReplaceAction.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\Generic;
23
24 use Civi\API\Exception\NotImplementedException;
25 use Civi\Api4\Utils\ActionUtil;
26
27 /**
28 * Replaces an existing set of $ENTITYs with a new one.
29 *
30 * This will select a group of existing $ENTITYs based on the `where` parameter.
31 * Each will be compared with the $ENTITYs passed in as `records`:
32 *
33 * - $ENTITYs in `records` that don't already exist will be created.
34 * - Existing $ENTITYs that are included in `records` will be updated.
35 * - Existing $ENTITYs that are omitted from `records` will be deleted.
36 *
37 * @method $this setRecords(array $records) Set array of records.
38 * @method array getRecords()
39 * @method $this setDefaults(array $defaults) Set array of defaults.
40 * @method array getDefaults()
41 * @method $this setReload(bool $reload) Specify whether complete objects will be returned after saving.
42 * @method bool getReload()
43 */
44 class BasicReplaceAction extends AbstractBatchAction {
45
46 /**
47 * Array of $ENTITY records.
48 *
49 * Should be in the same format as returned by `Get`.
50 *
51 * @var array
52 * @required
53 */
54 protected $records = [];
55
56 /**
57 * Array of default values.
58 *
59 * Will be merged into `records` before saving.
60 *
61 * **Note:** Values from the `where` clause that use the `=` operator are _also_ saved into each record;
62 * those do not need to be repeated here.
63 *
64 * @var array
65 */
66 protected $defaults = [];
67
68 /**
69 * Reload $ENTITYs after saving.
70 *
71 * By default this action typically returns partial records containing only the fields
72 * that were updated. Set `reload` to `true` to do an additional lookup after saving
73 * to return complete values for every $ENTITY.
74 *
75 * @var bool
76 */
77 protected $reload = FALSE;
78
79 /**
80 * @return \Civi\Api4\Result\ReplaceResult
81 */
82 public function execute() {
83 return parent::execute();
84 }
85
86 /**
87 * @inheritDoc
88 */
89 public function _run(Result $result) {
90 $items = $this->getBatchRecords();
91
92 // Copy defaults from where clause if the operator is =
93 foreach ($this->where as $clause) {
94 if (is_array($clause) && $clause[1] === '=') {
95 $this->defaults[$clause[0]] = $clause[2];
96 }
97 }
98
99 $idField = $this->getSelect()[0];
100 $toDelete = array_diff_key(array_column($items, NULL, $idField), array_flip(array_filter(\CRM_Utils_Array::collect($idField, $this->records))));
101
102 // Try to delegate to the Save action
103 try {
104 $saveAction = ActionUtil::getAction($this->getEntityName(), 'save');
105 $saveAction
106 ->setCheckPermissions($this->getCheckPermissions())
107 ->setReload($this->reload)
108 ->setRecords($this->records)
109 ->setDefaults($this->defaults);
110 $result->exchangeArray((array) $saveAction->execute());
111 }
112 // Fall back on Create/Update if Save doesn't exist
113 catch (NotImplementedException $e) {
114 foreach ($this->records as $record) {
115 $record += $this->defaults;
116 if (!empty($record[$idField])) {
117 $result[] = civicrm_api4($this->getEntityName(), 'update', [
118 'reload' => $this->reload,
119 'where' => [[$idField, '=', $record[$idField]]],
120 'values' => $record,
121 'checkPermissions' => $this->getCheckPermissions(),
122 ])->first();
123 }
124 else {
125 $result[] = civicrm_api4($this->getEntityName(), 'create', [
126 'values' => $record,
127 'checkPermissions' => $this->getCheckPermissions(),
128 ])->first();
129 }
130 }
131 }
132
133 if ($toDelete) {
134 $result->deleted = (array) civicrm_api4($this->getEntityName(), 'delete', [
135 'where' => [[$idField, 'IN', array_keys($toDelete)]],
136 'checkPermissions' => $this->getCheckPermissions(),
137 ]);
138 }
139 }
140
141 /**
142 * Set default value for a field.
143 * @param string $fieldName
144 * @param mixed $defaultValue
145 * @return $this
146 */
147 public function addDefault(string $fieldName, $defaultValue) {
148 $this->defaults[$fieldName] = $defaultValue;
149 return $this;
150 }
151
152 /**
153 * Add one or more records
154 * @param array ...$records
155 * @return $this
156 */
157 public function addRecord(array ...$records) {
158 $this->records = array_merge($this->records, $records);
159 return $this;
160 }
161
162 }