APIv4 - Improve joins test coverage
[civicrm-core.git] / Civi / Api4 / Generic / Traits / CustomValueActionTrait.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 * $Id$
18 *
19 */
20
21
22 namespace Civi\Api4\Generic\Traits;
23
24 use Civi\Api4\Utils\FormattingUtil;
25 use Civi\Api4\Utils\CoreUtil;
26
27 /**
28 * Helper functions for working with custom values
29 *
30 * @package Civi\Api4\Generic
31 */
32 trait CustomValueActionTrait {
33
34 public function __construct($customGroup, $actionName) {
35 $this->customGroup = $customGroup;
36 parent::__construct('CustomValue', $actionName, ['id', 'entity_id']);
37 }
38
39 /**
40 * Custom Group name if this is a CustomValue pseudo-entity.
41 *
42 * @var string
43 */
44 private $customGroup;
45
46 /**
47 * @inheritDoc
48 */
49 public function getEntityName() {
50 return 'Custom_' . $this->getCustomGroup();
51 }
52
53 /**
54 * @inheritDoc
55 */
56 protected function writeObjects($items) {
57 $result = [];
58 $fields = $this->entityFields();
59 foreach ($items as $item) {
60 FormattingUtil::formatWriteParams($item, $fields);
61
62 // Convert field names to custom_xx format
63 foreach ($fields as $name => $field) {
64 if (!empty($field['custom_field_id']) && isset($item[$name])) {
65 $item['custom_' . $field['custom_field_id']] = $item[$name];
66 unset($item[$name]);
67 }
68 }
69
70 $result[] = \CRM_Core_BAO_CustomValueTable::setValues($item);
71 }
72 return $result;
73 }
74
75 /**
76 * @inheritDoc
77 */
78 protected function deleteObjects($items) {
79 $customTable = CoreUtil::getCustomTableByName($this->getCustomGroup());
80 $ids = [];
81 foreach ($items as $item) {
82 \CRM_Utils_Hook::pre('delete', $this->getEntityName(), $item['id'], \CRM_Core_DAO::$_nullArray);
83 \CRM_Utils_SQL_Delete::from($customTable)
84 ->where('id = #value')
85 ->param('#value', $item['id'])
86 ->execute();
87 \CRM_Utils_Hook::post('delete', $this->getEntityName(), $item['id'], \CRM_Core_DAO::$_nullArray);
88 $ids[] = $item['id'];
89 }
90 return $ids;
91 }
92
93 /**
94 * @inheritDoc
95 */
96 protected function fillDefaults(&$params) {
97 foreach ($this->entityFields() as $name => $field) {
98 if (!isset($params[$name]) && isset($field['default_value'])) {
99 $params[$name] = $field['default_value'];
100 }
101 }
102 }
103
104 /**
105 * @return string
106 */
107 public function getCustomGroup() {
108 return $this->customGroup;
109 }
110
111 }