Merge pull request #17878 from civicrm/5.28
[civicrm-core.git] / Civi / Api4 / Generic / DAOUpdateAction.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 /**
25 * Update one or more $ENTITY with new values.
26 *
27 * Use the `where` clause (required) to select them.
28 */
29 class DAOUpdateAction extends AbstractUpdateAction {
30 use Traits\DAOActionTrait;
31
32 /**
33 * Criteria for selecting items to update.
34 *
35 * Required if no id is supplied in values.
36 *
37 * @var array
38 */
39 protected $where = [];
40
41 /**
42 * @inheritDoc
43 */
44 public function _run(Result $result) {
45 $this->formatWriteValues($this->values);
46 // Add ID from values to WHERE clause and check for mismatch
47 if (!empty($this->values['id'])) {
48 $wheres = array_column($this->where, NULL, 0);
49 if (!isset($wheres['id'])) {
50 $this->addWhere('id', '=', $this->values['id']);
51 }
52 elseif (!($wheres['id'][1] === '=' && $wheres['id'][2] == $this->values['id'])) {
53 throw new \Exception("Cannot update the id of an existing " . $this->getEntityName() . '.');
54 }
55 }
56
57 // Require WHERE if we didn't get an ID from values
58 if (!$this->where) {
59 throw new \API_Exception('Parameter "where" is required unless an id is supplied in values.');
60 }
61
62 // Update a single record by ID unless select requires more than id
63 if ($this->getSelect() === ['id'] && count($this->where) === 1 && $this->where[0][0] === 'id' && $this->where[0][1] === '=' && !empty($this->where[0][2])) {
64 $this->values['id'] = $this->where[0][2];
65 $result->exchangeArray($this->writeObjects([$this->values]));
66 return;
67 }
68
69 // Batch update 1 or more records based on WHERE clause
70 $items = $this->getBatchRecords();
71 foreach ($items as &$item) {
72 $item = $this->values + $item;
73 }
74
75 $result->exchangeArray($this->writeObjects($items));
76 }
77
78 }