Commit | Line | Data |
---|---|---|
19b53e5b C |
1 | <?php |
2 | ||
3 | namespace Civi\Api4\Generic; | |
4 | ||
5 | use Civi\API\Exception\NotImplementedException; | |
6 | ||
7 | /** | |
8 | * Update one or more records with new values. | |
9 | * | |
10 | * Use the where clause (required) to select them. | |
11 | */ | |
12 | class BasicUpdateAction extends AbstractUpdateAction { | |
13 | ||
14 | /** | |
15 | * @var callable | |
16 | * | |
17 | * Function(array $item, BasicUpdateAction $thisAction) => array | |
18 | */ | |
19 | private $setter; | |
20 | ||
21 | /** | |
22 | * BasicUpdateAction constructor. | |
23 | * | |
24 | * @param string $entityName | |
25 | * @param string $actionName | |
26 | * @param string|array $select | |
27 | * One or more fields to select from each matching item. | |
28 | * @param callable $setter | |
29 | * Function(array $item, BasicUpdateAction $thisAction) => array | |
30 | */ | |
31 | public function __construct($entityName, $actionName, $select = 'id', $setter = NULL) { | |
32 | parent::__construct($entityName, $actionName, $select); | |
33 | $this->setter = $setter; | |
34 | } | |
35 | ||
36 | /** | |
37 | * We pass the writeRecord function an array representing one item to update. | |
38 | * We expect to get the same format back. | |
39 | * | |
40 | * @param \Civi\Api4\Generic\Result $result | |
41 | * @throws \API_Exception | |
42 | * @throws \Civi\API\Exception\NotImplementedException | |
43 | */ | |
44 | public function _run(Result $result) { | |
45 | foreach ($this->getBatchRecords() as $item) { | |
46 | $result[] = $this->writeRecord($this->values + $item); | |
47 | } | |
48 | ||
49 | if (!$result->count()) { | |
50 | throw new \API_Exception('Cannot ' . $this->getActionName() . ' ' . $this->getEntityName() . ', no records found with ' . $this->whereClauseToString()); | |
51 | } | |
52 | } | |
53 | ||
54 | /** | |
55 | * This Basic Update class can be used in one of two ways: | |
56 | * | |
57 | * 1. Use this class directly by passing a callable ($setter) to the constructor. | |
58 | * 2. Extend this class and override this function. | |
59 | * | |
60 | * Either way, this function should return an array representing the one modified object. | |
61 | * | |
62 | * @param array $item | |
63 | * @return array | |
64 | * @throws \Civi\API\Exception\NotImplementedException | |
65 | */ | |
66 | protected function writeRecord($item) { | |
67 | if (is_callable($this->setter)) { | |
68 | return call_user_func($this->setter, $item, $this); | |
69 | } | |
70 | throw new NotImplementedException('Setter function not found for api4 ' . $this->getEntityName() . '::' . $this->getActionName()); | |
71 | } | |
72 | ||
73 | } |