api4 - Import CRM/, Civi/, templates/, ang/, css/, js/, xml/menu
[civicrm-core.git] / Civi / Api4 / Generic / DAODeleteAction.php
1 <?php
2
3 namespace Civi\Api4\Generic;
4
5 /**
6 * Delete one or more items, based on criteria specified in Where param (required).
7 */
8 class DAODeleteAction extends AbstractBatchAction {
9 use Traits\DAOActionTrait;
10
11 /**
12 * Batch delete function
13 */
14 public function _run(Result $result) {
15 $defaults = $this->getParamDefaults();
16 if ($defaults['where'] && !array_diff_key($this->where, $defaults['where'])) {
17 throw new \API_Exception('Cannot delete ' . $this->getEntityName() . ' with no "where" parameter specified');
18 }
19
20 $items = $this->getObjects();
21
22 if (!$items) {
23 throw new \API_Exception('Cannot delete ' . $this->getEntityName() . ', no records found with ' . $this->whereClauseToString());
24 }
25
26 $ids = $this->deleteObjects($items);
27
28 $result->exchangeArray($ids);
29 }
30
31 /**
32 * @param $items
33 * @return array
34 * @throws \API_Exception
35 */
36 protected function deleteObjects($items) {
37 $ids = [];
38 $baoName = $this->getBaoName();
39
40 if ($this->getCheckPermissions()) {
41 foreach ($items as $item) {
42 $this->checkContactPermissions($baoName, $item);
43 }
44 }
45
46 if ($this->getEntityName() !== 'EntityTag' && method_exists($baoName, 'del')) {
47 foreach ($items as $item) {
48 $args = [$item['id']];
49 $bao = call_user_func_array([$baoName, 'del'], $args);
50 if ($bao !== FALSE) {
51 $ids[] = ['id' => $item['id']];
52 }
53 else {
54 throw new \API_Exception("Could not delete {$this->getEntityName()} id {$item['id']}");
55 }
56 }
57 }
58 else {
59 foreach ($items as $item) {
60 $bao = new $baoName();
61 $bao->id = $item['id'];
62 // delete it
63 $action_result = $bao->delete();
64 if ($action_result) {
65 $ids[] = ['id' => $item['id']];
66 }
67 else {
68 throw new \API_Exception("Could not delete {$this->getEntityName()} id {$item['id']}");
69 }
70 }
71 }
72 return $ids;
73 }
74
75 }