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