28684ad9e51bacaf931bdbbce4c7af96ca8216a7
[civicrm-core.git] / Civi / Api4 / Generic / DAOUpdateAction.php
1 <?php
2
3 namespace Civi\Api4\Generic;
4
5 /**
6 * Update one or more records with new values.
7 *
8 * Use the where clause (required) to select them.
9 */
10 class DAOUpdateAction extends AbstractUpdateAction {
11 use Traits\DAOActionTrait;
12
13 /**
14 * Criteria for selecting items to update.
15 *
16 * Required if no id is supplied in values.
17 *
18 * @var array
19 */
20 protected $where = [];
21
22 /**
23 * @inheritDoc
24 */
25 public function _run(Result $result) {
26 // Add ID from values to WHERE clause and check for mismatch
27 if (!empty($this->values['id'])) {
28 $wheres = array_column($this->where, NULL, 0);
29 if (!isset($wheres['id'])) {
30 $this->addWhere('id', '=', $this->values['id']);
31 }
32 elseif (!($wheres['id'][1] === '=' && $wheres['id'][2] == $this->values['id'])) {
33 throw new \Exception("Cannot update the id of an existing " . $this->getEntityName() . '.');
34 }
35 }
36
37 // Require WHERE if we didn't get an ID from values
38 if (!$this->where) {
39 throw new \API_Exception('Parameter "where" is required unless an id is supplied in values.');
40 }
41
42 // Update a single record by ID unless select requires more than id
43 if ($this->getSelect() === ['id'] && count($this->where) === 1 && $this->where[0][0] === 'id' && $this->where[0][1] === '=' && !empty($this->where[0][2])) {
44 $this->values['id'] = $this->where[0][2];
45 $result->exchangeArray($this->writeObjects([$this->values]));
46 return;
47 }
48
49 // Batch update 1 or more records based on WHERE clause
50 $items = $this->getObjects();
51 foreach ($items as &$item) {
52 $item = $this->values + $item;
53 }
54
55 if (!$items) {
56 throw new \API_Exception('Cannot ' . $this->getActionName() . ' ' . $this->getEntityName() . ', no records found with ' . $this->whereClauseToString());
57 }
58
59 $result->exchangeArray($this->writeObjects($items));
60 }
61
62 }