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