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