Merge pull request #19973 from JMAConsulting/core_365_1
[civicrm-core.git] / Civi / Api4 / Generic / AbstractUpdateAction.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 */
18
19
20 namespace Civi\Api4\Generic;
21
22 use Civi\Api4\Event\ValidateValuesEvent;
23
24 /**
25 * Base class for all `Update` api actions
26 *
27 * @method $this setValues(array $values) Set all field values from an array of key => value pairs.
28 * @method array getValues() Get field values.
29 * @method $this setReload(bool $reload) Specify whether complete objects will be returned after saving.
30 * @method bool getReload()
31 *
32 * @package Civi\Api4\Generic
33 */
34 abstract class AbstractUpdateAction extends AbstractBatchAction {
35
36 /**
37 * Field values to update.
38 *
39 * @var array
40 * @required
41 */
42 protected $values = [];
43
44 /**
45 * Reload $ENTITIES after saving.
46 *
47 * Setting to `true` will load complete records and return them as the api result.
48 * If `false` the api usually returns only the fields specified to be updated.
49 *
50 * @var bool
51 */
52 protected $reload = FALSE;
53
54 /**
55 * @param string $fieldName
56 *
57 * @return mixed|null
58 */
59 public function getValue(string $fieldName) {
60 return $this->values[$fieldName] ?? NULL;
61 }
62
63 /**
64 * Add an item to the values array.
65 *
66 * @param string $fieldName
67 * @param mixed $value
68 * @return $this
69 */
70 public function addValue(string $fieldName, $value) {
71 $this->values[$fieldName] = $value;
72 return $this;
73 }
74
75 /**
76 * @throws \API_Exception
77 */
78 protected function validateValues() {
79 // FIXME: There should be a protocol to report a full list of errors... Perhaps a subclass of API_Exception?
80 $e = new ValidateValuesEvent($this, [$this->values], new \CRM_Utils_LazyArray(function () {
81 $existing = $this->getBatchAction()->setSelect(['*'])->execute();
82 $result = [];
83 foreach ($existing as $record) {
84 $result[] = ['old' => $record, 'new' => $this->values];
85 }
86 return $result;
87 }));
88 \Civi::dispatcher()->dispatch('civi.api4.validate', $e);
89 if (!empty($e->errors)) {
90 throw $e->toException();
91 }
92 }
93
94 }