APIv4 - Allow field options to be returned in multiple formats
[civicrm-core.git] / Civi / Api4 / Utils / FormattingUtil.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\Utils;
23
24 require_once 'api/v3/utils.php';
25
26 class FormattingUtil {
27
28 public static $pseudoConstantContexts = [
29 'name' => 'validate',
30 'abbr' => 'abbreviate',
31 'label' => 'get',
32 ];
33
34 /**
35 * Massage values into the format the BAO expects for a write operation
36 *
37 * @param $params
38 * @param $entity
39 * @param $fields
40 * @throws \API_Exception
41 */
42 public static function formatWriteParams(&$params, $entity, $fields) {
43 foreach ($fields as $name => $field) {
44 if (!empty($params[$name])) {
45 $value =& $params[$name];
46 // Hack for null values -- see comment below
47 if ($value === 'null') {
48 $value = 'Null';
49 }
50 self::formatInputValue($value, $name, $field, $entity);
51 // Ensure we have an array for serialized fields
52 if (!empty($field['serialize'] && !is_array($value))) {
53 $value = (array) $value;
54 }
55 }
56 /*
57 * Because of the wacky way that database values are saved we need to format
58 * some of the values here. In this strange world the string 'null' is used to
59 * unset values. Hence if we encounter true null we change it to string 'null'.
60 *
61 * If we encounter the string 'null' then we assume the user actually wants to
62 * set the value to string null. However since the string null is reserved for
63 * unsetting values we must change it. Another quirk of the DB_DataObject is
64 * that it allows 'Null' to be set, but any other variation of string 'null'
65 * will be converted to true null, e.g. 'nuLL', 'NUlL' etc. so we change it to
66 * 'Null'.
67 */
68 elseif (array_key_exists($name, $params) && $params[$name] === NULL) {
69 $params[$name] = 'null';
70 }
71 }
72
73 \CRM_Utils_API_HTMLInputCoder::singleton()->encodeRow($params);
74 }
75
76 /**
77 * Transform raw api input to appropriate format for use in a SQL query.
78 *
79 * This is used by read AND write actions (Get, Create, Update, Replace)
80 *
81 * @param $value
82 * @param string $fieldName
83 * @param array $fieldSpec
84 * @param string $entity
85 * Ex: 'Contact', 'Domain'
86 * @throws \API_Exception
87 */
88 public static function formatInputValue(&$value, $fieldName, $fieldSpec, $entity) {
89 // Evaluate pseudoconstant suffix
90 $suffix = strpos($fieldName, ':');
91 if ($suffix) {
92 $options = self::getPseudoconstantList($fieldSpec['entity'], $fieldSpec['name'], substr($fieldName, $suffix + 1));
93 $value = self::replacePseudoconstant($options, $value, TRUE);
94 }
95 elseif (is_array($value)) {
96 foreach ($value as &$val) {
97 self::formatInputValue($val, $fieldName, $fieldSpec, $entity);
98 }
99 return;
100 }
101 $fk = $fieldSpec['name'] == 'id' ? $entity : $fieldSpec['fk_entity'] ?? NULL;
102
103 if ($fk === 'Domain' && $value === 'current_domain') {
104 $value = \CRM_Core_Config::domainID();
105 }
106
107 if ($fk === 'Contact' && !is_numeric($value)) {
108 $value = \_civicrm_api3_resolve_contactID($value);
109 if ('unknown-user' === $value) {
110 throw new \API_Exception("\"{$fieldSpec['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldSpec['name'], "type" => "integer"]);
111 }
112 }
113
114 switch ($fieldSpec['data_type'] ?? NULL) {
115 case 'Timestamp':
116 $value = date('Y-m-d H:i:s', strtotime($value));
117 break;
118
119 case 'Date':
120 $value = date('Ymd', strtotime($value));
121 break;
122 }
123
124 $hic = \CRM_Utils_API_HTMLInputCoder::singleton();
125 if (!$hic->isSkippedField($fieldSpec['name'])) {
126 $value = $hic->encodeValue($value);
127 }
128 }
129
130 /**
131 * Unserialize raw DAO values and convert to correct type
132 *
133 * @param array $results
134 * @param array $fields
135 * @param string $entity
136 * @param string $action
137 * @throws \API_Exception
138 * @throws \CRM_Core_Exception
139 */
140 public static function formatOutputValues(&$results, $fields, $entity, $action = 'get') {
141 $fieldOptions = [];
142 foreach ($results as &$result) {
143 $contactTypePaths = [];
144 foreach ($result as $fieldExpr => $value) {
145 $field = $fields[$fieldExpr] ?? NULL;
146 $dataType = $field['data_type'] ?? ($fieldExpr == 'id' ? 'Integer' : NULL);
147 if ($field) {
148 // Evaluate pseudoconstant suffixes
149 $suffix = strrpos($fieldExpr, ':');
150 if ($suffix) {
151 $fieldName = empty($field['custom_field_id']) ? $field['name'] : 'custom_' . $field['custom_field_id'];
152 $fieldOptions[$fieldExpr] = $fieldOptions[$fieldExpr] ?? self::getPseudoconstantList($field['entity'], $fieldName, substr($fieldExpr, $suffix + 1), $result, $action);
153 $dataType = NULL;
154 }
155 if (!empty($field['serialize'])) {
156 if (is_string($value)) {
157 $value = \CRM_Core_DAO::unSerializeField($value, $field['serialize']);
158 }
159 }
160 if (isset($fieldOptions[$fieldExpr])) {
161 $value = self::replacePseudoconstant($fieldOptions[$fieldExpr], $value);
162 }
163 // Keep track of contact types for self::contactFieldsToRemove
164 if ($value && isset($field['entity']) && $field['entity'] === 'Contact' && $field['name'] === 'contact_type') {
165 $prefix = strrpos($fieldExpr, '.');
166 $contactTypePaths[$prefix ? substr($fieldExpr, 0, $prefix + 1) : ''] = $value;
167 }
168 }
169 $result[$fieldExpr] = self::convertDataType($value, $dataType);
170 }
171 // Remove inapplicable contact fields
172 foreach ($contactTypePaths as $prefix => $contactType) {
173 \CRM_Utils_Array::remove($result, self::contactFieldsToRemove($contactType, $prefix));
174 }
175 }
176 }
177
178 /**
179 * Retrieves pseudoconstant option list for a field.
180 *
181 * @param string $entity
182 * Name of api entity
183 * @param string $fieldName
184 * @param string $valueType
185 * name|label|abbr from self::$pseudoConstantContexts
186 * @param array $params
187 * Other values for this object
188 * @param string $action
189 * @return array
190 * @throws \API_Exception
191 */
192 public static function getPseudoconstantList($entity, $fieldName, $valueType, $params = [], $action = 'get') {
193 $context = self::$pseudoConstantContexts[$valueType] ?? NULL;
194 if (!$context) {
195 throw new \API_Exception('Illegal expression');
196 }
197 $baoName = CoreUtil::getBAOFromApiName($entity);
198 // Use BAO::buildOptions if possible
199 if ($baoName) {
200 $options = $baoName::buildOptions($fieldName, $context, $params);
201 }
202 // Fallback for option lists that exist in the api but not the BAO - note: $valueType gets ignored here
203 if (!isset($options) || $options === FALSE) {
204 $options = civicrm_api4($entity, 'getFields', ['action' => $action, 'loadOptions' => TRUE, 'where' => [['name', '=', $fieldName]]])[0]['options'] ?? NULL;
205 }
206 if (is_array($options)) {
207 return $options;
208 }
209 throw new \API_Exception("No option list found for '$fieldName'");
210 }
211
212 /**
213 * Replaces value (or an array of values) with options from a pseudoconstant list.
214 *
215 * The direction of lookup defaults to transforming ids to option values for api output;
216 * for api input, set $reverse = TRUE to transform option values to ids.
217 *
218 * @param array $options
219 * @param string|string[] $value
220 * @param bool $reverse
221 * Is this a reverse lookup (for transforming input instead of output)
222 * @return array|mixed|null
223 */
224 public static function replacePseudoconstant($options, $value, $reverse = FALSE) {
225 $matches = [];
226 foreach ((array) $value as $val) {
227 if (!$reverse && isset($options[$val])) {
228 $matches[] = $options[$val];
229 }
230 elseif ($reverse && array_search($val, $options) !== FALSE) {
231 $matches[] = array_search($val, $options);
232 }
233 }
234 return is_array($value) ? $matches : $matches[0] ?? NULL;
235 }
236
237 /**
238 * @param mixed $value
239 * @param string $dataType
240 * @return mixed
241 */
242 public static function convertDataType($value, $dataType) {
243 if (isset($value) && $dataType) {
244 if (is_array($value)) {
245 foreach ($value as $key => $val) {
246 $value[$key] = self::convertDataType($val, $dataType);
247 }
248 return $value;
249 }
250
251 switch ($dataType) {
252 case 'Boolean':
253 return (bool) $value;
254
255 case 'Integer':
256 return (int) $value;
257
258 case 'Money':
259 case 'Float':
260 return (float) $value;
261 }
262 }
263 return $value;
264 }
265
266 /**
267 * Lists all field names (including suffixed variants) that should be removed for a given contact type.
268 *
269 * @param string $contactType
270 * Individual|Organization|Household
271 * @param string $prefix
272 * Path at which these fields are found, e.g. "address.contact."
273 * @return array
274 */
275 public static function contactFieldsToRemove($contactType, $prefix) {
276 if (!isset(\Civi::$statics[__CLASS__][__FUNCTION__][$contactType])) {
277 \Civi::$statics[__CLASS__][__FUNCTION__][$contactType] = [];
278 foreach (\CRM_Contact_DAO_Contact::fields() as $field) {
279 if (!empty($field['contactType']) && $field['contactType'] != $contactType) {
280 \Civi::$statics[__CLASS__][__FUNCTION__][$contactType][] = $field['name'];
281 // Include suffixed variants like prefix_id:label
282 if (!empty($field['pseudoconstant'])) {
283 foreach (array_keys(self::$pseudoConstantContexts) as $suffix) {
284 \Civi::$statics[__CLASS__][__FUNCTION__][$contactType][] = $field['name'] . ':' . $suffix;
285 }
286 }
287 }
288 }
289 }
290 // Add prefix paths
291 return array_map(function($name) use ($prefix) {
292 return $prefix . $name;
293 }, \Civi::$statics[__CLASS__][__FUNCTION__][$contactType]);
294 }
295
296 }