api4 - Import CRM/, Civi/, templates/, ang/, css/, js/, xml/menu
[civicrm-core.git] / Civi / Api4 / Generic / BasicCreateAction.php
1 <?php
2
3 namespace Civi\Api4\Generic;
4
5 use Civi\API\Exception\NotImplementedException;
6
7 /**
8 * Create a new object from supplied values.
9 *
10 * This function will create 1 new object. It cannot be used to update existing objects. Use the Update or Replace actions for that.
11 */
12 class BasicCreateAction extends AbstractCreateAction {
13
14 /**
15 * @var callable
16 *
17 * Function(array $item, BasicCreateAction $thisAction) => array
18 */
19 private $setter;
20
21 /**
22 * Basic Create constructor.
23 *
24 * @param string $entityName
25 * @param string $actionName
26 * @param callable $setter
27 * Function(array $item, BasicCreateAction $thisAction) => array
28 */
29 public function __construct($entityName, $actionName, $setter = NULL) {
30 parent::__construct($entityName, $actionName);
31 $this->setter = $setter;
32 }
33
34 /**
35 * We pass the writeRecord function an array representing one item to write.
36 * We expect to get the same format back.
37 *
38 * @param \Civi\Api4\Generic\Result $result
39 */
40 public function _run(Result $result) {
41 $this->validateValues();
42 $result->exchangeArray([$this->writeRecord($this->values)]);
43 }
44
45 /**
46 * This Basic Create class can be used in one of two ways:
47 *
48 * 1. Use this class directly by passing a callable ($setter) to the constructor.
49 * 2. Extend this class and override this function.
50 *
51 * Either way, this function should return an array representing the one new object.
52 *
53 * @param array $item
54 * @return array
55 * @throws \Civi\API\Exception\NotImplementedException
56 */
57 protected function writeRecord($item) {
58 if (is_callable($this->setter)) {
59 return call_user_func($this->setter, $item, $this);
60 }
61 throw new NotImplementedException('Setter function not found for api4 ' . $this->getEntityName() . '::' . $this->getActionName());
62 }
63
64 }