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