Merge pull request #20523 from eileenmcnaughton/pcp2
[civicrm-core.git] / Civi / Api4 / Generic / DAODeleteAction.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\UnauthorizedException;
23 use Civi\Api4\Utils\CoreUtil;
24
25 /**
26 * Delete one or more $ENTITIES.
27 *
28 * $ENTITIES are deleted based on criteria specified in `where` parameter (required).
29 */
30 class DAODeleteAction extends AbstractBatchAction {
31 use Traits\DAOActionTrait;
32
33 /**
34 * Batch delete function
35 */
36 public function _run(Result $result) {
37 $defaults = $this->getParamDefaults();
38 if ($defaults['where'] && $this->where === $defaults['where']) {
39 throw new \API_Exception('Cannot delete ' . $this->getEntityName() . ' with no "where" parameter specified');
40 }
41
42 $items = $this->getBatchRecords();
43
44 if ($this->getCheckPermissions()) {
45 foreach ($items as $key => $item) {
46 if (!CoreUtil::checkAccessRecord($this, $item, \CRM_Core_Session::getLoggedInContactID() ?: 0)) {
47 throw new UnauthorizedException("ACL check failed");
48 }
49 $items[$key]['check_permissions'] = TRUE;
50 }
51 }
52 if ($items) {
53 $result->exchangeArray($this->deleteObjects($items));
54 }
55 }
56
57 /**
58 * @param $items
59 * @return array
60 * @throws \API_Exception
61 */
62 protected function deleteObjects($items) {
63 $ids = [];
64 $baoName = $this->getBaoName();
65
66 if ($this->getEntityName() !== 'EntityTag' && method_exists($baoName, 'del')) {
67 foreach ($items as $item) {
68 $args = [$item['id']];
69 $bao = call_user_func_array([$baoName, 'del'], $args);
70 if ($bao !== FALSE) {
71 $ids[] = ['id' => $item['id']];
72 }
73 else {
74 throw new \API_Exception("Could not delete {$this->getEntityName()} id {$item['id']}");
75 }
76 }
77 }
78 else {
79 foreach ($baoName::deleteRecords($items) as $instance) {
80 $ids[] = ['id' => $instance->id];
81 }
82 }
83 return $ids;
84 }
85
86 }