4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 namespace Civi\Api4\Generic
;
15 use Civi\API\Exception\NotImplementedException
;
16 use Civi\Api4\Utils\CoreUtil
;
21 class BasicSaveAction
extends AbstractSaveAction
{
25 * Function(array $item, BasicCreateAction $thisAction): array
30 * Basic Save constructor.
32 * @param string $entityName
33 * @param string $actionName
34 * @param callable $setter
36 public function __construct($entityName, $actionName, $setter = NULL) {
37 parent
::__construct($entityName, $actionName);
38 // Accept setter as 4th param for now, but emit deprecated warning
39 $this->setter
= func_get_args()[3] ??
NULL;
41 \CRM_Core_Error
::deprecatedWarning(__CLASS__
. ' constructor received $setter as 4th param; it should be the 3rd as the $select param has been removed');
44 $this->setter
= $setter;
49 * We pass the writeRecord function an array representing one item to write.
50 * We expect to get the same format back.
52 * @param \Civi\Api4\Generic\Result $result
54 public function _run(Result
$result) {
55 $idField = CoreUtil
::getIdFieldName($this->getEntityName());
56 foreach ($this->records
as &$record) {
57 $record +
= $this->defaults
;
58 $this->formatWriteValues($record);
59 $this->matchExisting($record);
61 $this->validateValues();
62 foreach ($this->records
as $item) {
63 $result[] = $this->writeRecord($item);
66 /** @var BasicGetAction $get */
67 $get = \Civi\API\Request
::create($this->getEntityName(), 'get', ['version' => 4]);
69 ->setCheckPermissions($this->getCheckPermissions())
70 ->addWhere($idField, 'IN', (array) $result->column($idField));
71 $result->exchangeArray((array) $get->execute());
76 * This Basic Save class can be used in one of two ways:
78 * 1. Use this class directly by passing a callable ($setter) to the constructor.
79 * 2. Extend this class and override this function.
81 * Either way, this function should return an array representing the one new object.
85 * @throws \Civi\API\Exception\NotImplementedException
87 protected function writeRecord($item) {
88 if (is_callable($this->setter
)) {
89 $this->addCallbackToDebugOutput($this->setter
);
90 return call_user_func($this->setter
, $item, $this);
92 throw new NotImplementedException('Setter function not found for api4 ' . $this->getEntityName() . '::' . $this->getActionName());