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 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 namespace Civi\Api4\Generic
;
22 use Civi\API\Exception\NotImplementedException
;
25 * $ACTION one or more $ENTITIES.
27 * If saving more than one new $ENTITY with similar values, use the `defaults` parameter.
29 * Set `reload` if you need the api to return complete $ENTITY records.
31 class BasicSaveAction
extends AbstractSaveAction
{
36 * Function(array $item, BasicCreateAction $thisAction) => array
41 * Basic Create constructor.
43 * @param string $entityName
44 * @param string $actionName
45 * @param string $idField
46 * @param callable $setter
47 * Function(array $item, BasicCreateAction $thisAction) => array
49 public function __construct($entityName, $actionName, $idField = 'id', $setter = NULL) {
50 parent
::__construct($entityName, $actionName, $idField);
51 $this->setter
= $setter;
55 * We pass the writeRecord function an array representing one item to write.
56 * We expect to get the same format back.
58 * @param \Civi\Api4\Generic\Result $result
60 public function _run(Result
$result) {
61 foreach ($this->records
as &$record) {
62 $record +
= $this->defaults
;
63 $this->formatWriteValues($record);
65 $this->validateValues();
66 foreach ($this->records
as $item) {
67 $result[] = $this->writeRecord($item);
70 /** @var BasicGetAction $get */
71 $get = \Civi\API\Request
::create($this->getEntityName(), 'get', ['version' => 4]);
73 ->setCheckPermissions($this->getCheckPermissions())
74 ->addWhere($this->getIdField(), 'IN', (array) $result->column($this->getIdField()));
75 $result->exchangeArray((array) $get->execute());
80 * This Basic Save class can be used in one of two ways:
82 * 1. Use this class directly by passing a callable ($setter) to the constructor.
83 * 2. Extend this class and override this function.
85 * Either way, this function should return an array representing the one new object.
89 * @throws \Civi\API\Exception\NotImplementedException
91 protected function writeRecord($item) {
92 if (is_callable($this->setter
)) {
93 $this->addCallbackToDebugOutput($this->setter
);
94 return call_user_func($this->setter
, $item, $this);
96 throw new NotImplementedException('Setter function not found for api4 ' . $this->getEntityName() . '::' . $this->getActionName());