Partially rollback changes to `$userID`. Merely lay groundwork for future update.
[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 */
18
19
20 namespace Civi\Api4\Generic;
21
22 use Civi\API\Exception\UnauthorizedException;
23 use Civi\Api4\Utils\CoreUtil;
24
25 /**
26 * Update one or more $ENTITY with new values.
27 *
28 * Use the `where` clause (required) to select them.
29 */
30 class DAOUpdateAction extends AbstractUpdateAction {
31 use Traits\DAOActionTrait;
32
33 /**
34 * Criteria for selecting items to update.
35 *
36 * Required if no id is supplied in values.
37 *
38 * @var array
39 */
40 protected $where = [];
41
42 /**
43 * @inheritDoc
44 */
45 public function _run(Result $result) {
46 $this->formatWriteValues($this->values);
47 // Add ID from values to WHERE clause and check for mismatch
48 if (!empty($this->values['id'])) {
49 $wheres = array_column($this->where, NULL, 0);
50 if (!isset($wheres['id'])) {
51 $this->addWhere('id', '=', $this->values['id']);
52 }
53 elseif (!($wheres['id'][1] === '=' && $wheres['id'][2] == $this->values['id'])) {
54 throw new \Exception("Cannot update the id of an existing " . $this->getEntityName() . '.');
55 }
56 }
57
58 // Require WHERE if we didn't get an ID from values
59 if (!$this->where) {
60 throw new \API_Exception('Parameter "where" is required unless an id is supplied in values.');
61 }
62
63 // Update a single record by ID unless select requires more than id
64 if ($this->getSelect() === ['id'] && count($this->where) === 1 && $this->where[0][0] === 'id' && $this->where[0][1] === '=' && !empty($this->where[0][2])) {
65 $this->values['id'] = $this->where[0][2];
66 if ($this->checkPermissions && !CoreUtil::checkAccessRecord($this, $this->values, \CRM_Core_Session::getLoggedInContactID() ?: 0)) {
67 throw new UnauthorizedException("ACL check failed");
68 }
69 $items = [$this->values];
70 $this->validateValues();
71 $result->exchangeArray($this->writeObjects($items));
72 return;
73 }
74
75 // Batch update 1 or more records based on WHERE clause
76 $items = $this->getBatchRecords();
77 foreach ($items as &$item) {
78 $item = $this->values + $item;
79 if ($this->checkPermissions && !CoreUtil::checkAccessRecord($this, $item, \CRM_Core_Session::getLoggedInContactID() ?: 0)) {
80 throw new UnauthorizedException("ACL check failed");
81 }
82 }
83
84 $this->validateValues();
85 $result->exchangeArray($this->writeObjects($items));
86 }
87
88 }