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