Merge branch '5.48'
[civicrm-core.git] / Civi / Api4 / Generic / DAODeleteAction.php
CommitLineData
19b53e5b
C
1<?php
2
380f3545
TO
3/*
4 +--------------------------------------------------------------------+
41498ac5 5 | Copyright CiviCRM LLC. All rights reserved. |
380f3545 6 | |
41498ac5
TO
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 |
380f3545
TO
10 +--------------------------------------------------------------------+
11 */
12
19b53e5b
C
13namespace Civi\Api4\Generic;
14
929a9585
CW
15use Civi\API\Exception\UnauthorizedException;
16use Civi\Api4\Utils\CoreUtil;
ef0a9972 17use Civi\Api4\Utils\ReflectionUtils;
929a9585 18
19b53e5b 19/**
e3c6d5ff 20 * Delete one or more $ENTITIES.
fc95d9a5 21 *
e3c6d5ff 22 * $ENTITIES are deleted based on criteria specified in `where` parameter (required).
19b53e5b
C
23 */
24class DAODeleteAction extends AbstractBatchAction {
25 use Traits\DAOActionTrait;
26
27 /**
28 * Batch delete function
29 */
30 public function _run(Result $result) {
31 $defaults = $this->getParamDefaults();
8a0c3604 32 if ($defaults['where'] && $this->where === $defaults['where']) {
19b53e5b
C
33 throw new \API_Exception('Cannot delete ' . $this->getEntityName() . ' with no "where" parameter specified');
34 }
35
3c7c8fa6 36 $items = $this->getBatchRecords();
1d3cbc3c
CW
37
38 if ($this->getCheckPermissions()) {
39 foreach ($items as $key => $item) {
70da3927 40 if (!CoreUtil::checkAccessRecord($this, $item, \CRM_Core_Session::getLoggedInContactID() ?: 0)) {
1d3cbc3c
CW
41 throw new UnauthorizedException("ACL check failed");
42 }
43 $items[$key]['check_permissions'] = TRUE;
44 }
45 }
8a0c3604
CW
46 if ($items) {
47 $result->exchangeArray($this->deleteObjects($items));
19b53e5b 48 }
19b53e5b
C
49 }
50
51 /**
52 * @param $items
53 * @return array
54 * @throws \API_Exception
55 */
56 protected function deleteObjects($items) {
57 $ids = [];
58 $baoName = $this->getBaoName();
59
ef0a9972
CW
60 // Use BAO::del() method if it is not deprecated
61 if (method_exists($baoName, 'del') && !ReflectionUtils::isMethodDeprecated($baoName, 'del')) {
19b53e5b
C
62 foreach ($items as $item) {
63 $args = [$item['id']];
64 $bao = call_user_func_array([$baoName, 'del'], $args);
65 if ($bao !== FALSE) {
66 $ids[] = ['id' => $item['id']];
67 }
68 else {
69 throw new \API_Exception("Could not delete {$this->getEntityName()} id {$item['id']}");
70 }
71 }
72 }
73 else {
236f858e
CW
74 foreach ($baoName::deleteRecords($items) as $instance) {
75 $ids[] = ['id' => $instance->id];
19b53e5b
C
76 }
77 }
78 return $ids;
79 }
80
81}