Merge pull request #18281 from sunilpawar/report_48
[civicrm-core.git] / Civi / Api4 / Generic / BasicUpdateAction.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\NotImplementedException;
23
24 /**
25 * Update one or more $ENTITY with new values.
26 *
27 * Use the `where` clause (required) to select them.
28 */
29 class BasicUpdateAction extends AbstractUpdateAction {
30
31 /**
32 * @var callable
33 * Function(array $item, BasicUpdateAction $thisAction): array
34 */
35 private $setter;
36
37 /**
38 * BasicUpdateAction constructor.
39 *
40 * @param string $entityName
41 * @param string $actionName
42 * @param string|array $select
43 * One or more fields to select from each matching item.
44 * @param callable $setter
45 */
46 public function __construct($entityName, $actionName, $select = 'id', $setter = NULL) {
47 parent::__construct($entityName, $actionName, $select);
48 $this->setter = $setter;
49 }
50
51 /**
52 * We pass the writeRecord function an array representing one item to update.
53 * We expect to get the same format back.
54 *
55 * @param \Civi\Api4\Generic\Result $result
56 * @throws \API_Exception
57 * @throws \Civi\API\Exception\NotImplementedException
58 */
59 public function _run(Result $result) {
60 $this->formatWriteValues($this->values);
61 foreach ($this->getBatchRecords() as $item) {
62 $result[] = $this->writeRecord($this->values + $item);
63 }
64 }
65
66 /**
67 * This Basic Update class can be used in one of two ways:
68 *
69 * 1. Use this class directly by passing a callable ($setter) to the constructor.
70 * 2. Extend this class and override this function.
71 *
72 * Either way, this function should return an array representing the one modified object.
73 *
74 * @param array $item
75 * @return array
76 * @throws \Civi\API\Exception\NotImplementedException
77 */
78 protected function writeRecord($item) {
79 if (is_callable($this->setter)) {
80 $this->addCallbackToDebugOutput($this->setter);
81 return call_user_func($this->setter, $item, $this);
82 }
83 throw new NotImplementedException('Setter function not found for api4 ' . $this->getEntityName() . '::' . $this->getActionName());
84 }
85
86 }