Merge pull request #17879 from colemanw/relCacheApi
[civicrm-core.git] / Civi / Api4 / Generic / BasicBatchAction.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 * $ACTION one or more $ENTITIES.
26 *
27 * $ENTITIES are selected based on criteria specified in `where` parameter (required).
28 *
29 * @package Civi\Api4\Generic
30 */
31 class BasicBatchAction extends AbstractBatchAction {
32
33 /**
34 * @var callable
35 *
36 * Function(array $item, BasicBatchAction $thisAction) => array
37 */
38 private $doer;
39
40 /**
41 * BasicBatchAction constructor.
42 *
43 * ```php
44 * $myAction = new BasicBatchAction($entityName, $actionName, function($item) {
45 * // Do something with $item
46 * $return $item;
47 * });
48 * ```
49 *
50 * @param string $entityName
51 * @param string $actionName
52 * @param string|array $select
53 * One or more fields to select from each matching item.
54 * @param callable $doer
55 * Function(array $item, BasicBatchAction $thisAction) => array
56 */
57 public function __construct($entityName, $actionName, $select = 'id', $doer = NULL) {
58 parent::__construct($entityName, $actionName, $select);
59 $this->doer = $doer;
60 }
61
62 /**
63 * We pass the doTask function an array representing one item to update.
64 * We expect to get the same format back.
65 *
66 * @param \Civi\Api4\Generic\Result $result
67 */
68 public function _run(Result $result) {
69 foreach ($this->getBatchRecords() as $item) {
70 $result[] = $this->doTask($item);
71 }
72 }
73
74 /**
75 * This Basic Batch class can be used in one of two ways:
76 *
77 * 1. Use this class directly by passing a callable ($doer) to the constructor.
78 * 2. Extend this class and override this function.
79 *
80 * Either way, this function should return an array with an output record
81 * for the item.
82 *
83 * @param array $item
84 * @return array
85 * @throws \Civi\API\Exception\NotImplementedException
86 */
87 protected function doTask($item) {
88 if (is_callable($this->doer)) {
89 $this->addCallbackToDebugOutput($this->doer);
90 return call_user_func($this->doer, $item, $this);
91 }
92 throw new NotImplementedException('Doer function not found for api4 ' . $this->getEntityName() . '::' . $this->getActionName());
93 }
94
95 }