Merge pull request #18084 from civicrm/5.28
[civicrm-core.git] / Civi / Api4 / Generic / BasicSaveAction.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 * @inheritDoc
26 */
27 class BasicSaveAction extends AbstractSaveAction {
28
29 /**
30 * @var callable
31 * Function(array $item, BasicCreateAction $thisAction): array
32 */
33 private $setter;
34
35 /**
36 * Basic Save constructor.
37 *
38 * @param string $entityName
39 * @param string $actionName
40 * @param string $idField
41 * @param callable $setter
42 */
43 public function __construct($entityName, $actionName, $idField = 'id', $setter = NULL) {
44 parent::__construct($entityName, $actionName, $idField);
45 $this->setter = $setter;
46 }
47
48 /**
49 * We pass the writeRecord function an array representing one item to write.
50 * We expect to get the same format back.
51 *
52 * @param \Civi\Api4\Generic\Result $result
53 */
54 public function _run(Result $result) {
55 foreach ($this->records as &$record) {
56 $record += $this->defaults;
57 $this->formatWriteValues($record);
58 }
59 $this->validateValues();
60 foreach ($this->records as $item) {
61 $result[] = $this->writeRecord($item);
62 }
63 if ($this->reload) {
64 /** @var BasicGetAction $get */
65 $get = \Civi\API\Request::create($this->getEntityName(), 'get', ['version' => 4]);
66 $get
67 ->setCheckPermissions($this->getCheckPermissions())
68 ->addWhere($this->getIdField(), 'IN', (array) $result->column($this->getIdField()));
69 $result->exchangeArray((array) $get->execute());
70 }
71 }
72
73 /**
74 * This Basic Save class can be used in one of two ways:
75 *
76 * 1. Use this class directly by passing a callable ($setter) to the constructor.
77 * 2. Extend this class and override this function.
78 *
79 * Either way, this function should return an array representing the one new object.
80 *
81 * @param array $item
82 * @return array
83 * @throws \Civi\API\Exception\NotImplementedException
84 */
85 protected function writeRecord($item) {
86 if (is_callable($this->setter)) {
87 $this->addCallbackToDebugOutput($this->setter);
88 return call_user_func($this->setter, $item, $this);
89 }
90 throw new NotImplementedException('Setter function not found for api4 ' . $this->getEntityName() . '::' . $this->getActionName());
91 }
92
93 }