APIv4 - Add checkAccess action
[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 use Civi\API\Exception\UnauthorizedException;
24 use Civi\Api4\Utils\CoreUtil;
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 * Function(array $item, BasicBatchAction $thisAction): array
38 */
39 private $doer;
40
41 /**
42 * BasicBatchAction constructor.
43 *
44 * ```php
45 * $myAction = new BasicBatchAction($entityName, $actionName, function($item) {
46 * // Do something with $item
47 * $return $item;
48 * });
49 * ```
50 *
51 * @param string $entityName
52 * @param string $actionName
53 * @param string|array $select
54 * One or more fields to select from each matching item.
55 * @param callable $doer
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 if ($this->checkPermissions && !CoreUtil::checkAccess($this->getEntityName(), $this->getActionName(), $item)) {
71 throw new UnauthorizedException("ACL check failed");
72 }
73 $result[] = $this->doTask($item);
74 }
75 }
76
77 /**
78 * This Basic Batch class can be used in one of two ways:
79 *
80 * 1. Use this class directly by passing a callable ($doer) to the constructor.
81 * 2. Extend this class and override this function.
82 *
83 * Either way, this function should return an array with an output record
84 * for the item.
85 *
86 * @param array $item
87 * @return array
88 * @throws \Civi\API\Exception\NotImplementedException
89 */
90 protected function doTask($item) {
91 if (is_callable($this->doer)) {
92 $this->addCallbackToDebugOutput($this->doer);
93 return call_user_func($this->doer, $item, $this);
94 }
95 throw new NotImplementedException('Doer function not found for api4 ' . $this->getEntityName() . '::' . $this->getActionName());
96 }
97
98 }