APIv4 - When running validateValues(), fire an event
[civicrm-core.git] / Civi / Api4 / Generic / AbstractUpdateAction.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
13/**
14 *
15 * @package CRM
ca5cec67 16 * @copyright CiviCRM LLC https://civicrm.org/licensing
380f3545
TO
17 */
18
19
19b53e5b
C
20namespace Civi\Api4\Generic;
21
4bf92107
TO
22use Civi\Api4\Event\ValidateValuesEvent;
23
19b53e5b 24/**
fc95d9a5 25 * Base class for all `Update` api actions
19b53e5b
C
26 *
27 * @method $this setValues(array $values) Set all field values from an array of key => value pairs.
19b53e5b
C
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 */
34abstract class AbstractUpdateAction extends AbstractBatchAction {
35
36 /**
37 * Field values to update.
38 *
39 * @var array
40 * @required
41 */
42 protected $values = [];
43
44 /**
e3c6d5ff 45 * Reload $ENTITIES after saving.
19b53e5b 46 *
fc95d9a5
CW
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.
19b53e5b
C
49 *
50 * @var bool
51 */
52 protected $reload = FALSE;
53
54 /**
121ec912 55 * @param string $fieldName
19b53e5b
C
56 *
57 * @return mixed|null
58 */
121ec912 59 public function getValue(string $fieldName) {
2e1f50d6 60 return $this->values[$fieldName] ?? NULL;
121ec912
CW
61 }
62
63 /**
fc95d9a5
CW
64 * Add an item to the values array.
65 *
121ec912
CW
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;
19b53e5b
C
73 }
74
a9aac3bf
TO
75 /**
76 * @throws \API_Exception
77 */
78 protected function validateValues() {
4bf92107
TO
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]);
81 \Civi::dispatcher()->dispatch('civi.api4.validate', $e);
82 if (!empty($e->errors)) {
83 throw $e->toException();
84 }
a9aac3bf
TO
85 }
86
19b53e5b 87}