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