Merge pull request #17209 from civicrm/5.25
[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 $optionValue
185 * @param array $params
186 * Other values for this object
187 * @param string $action
188 * @return array
189 * @throws \API_Exception
190 */
191 public static function getPseudoconstantList($entity, $fieldName, $optionValue, $params = [], $action = 'get') {
192 $context = self::$pseudoConstantContexts[$optionValue] ?? NULL;
193 if (!$context) {
194 throw new \API_Exception('Illegal expression');
195 }
196 $baoName = CoreUtil::getBAOFromApiName($entity);
197 // Use BAO::buildOptions if possible
198 if ($baoName) {
199 $options = $baoName::buildOptions($fieldName, $context, $params);
200 }
201 // Fallback for non-bao based entities
202 if (!isset($options)) {
203 $options = civicrm_api4($entity, 'getFields', ['action' => $action, 'loadOptions' => TRUE, 'where' => [['name', '=', $fieldName]]])[0]['options'] ?? NULL;
204 }
205 if (is_array($options)) {
206 return $options;
207 }
208 throw new \API_Exception("No option list found for '$fieldName'");
209 }
210
211 /**
212 * Replaces value (or an array of values) with options from a pseudoconstant list.
213 *
214 * The direction of lookup defaults to transforming ids to option values for api output;
215 * for api input, set $reverse = TRUE to transform option values to ids.
216 *
217 * @param array $options
218 * @param string|string[] $value
219 * @param bool $reverse
220 * Is this a reverse lookup (for transforming input instead of output)
221 * @return array|mixed|null
222 */
223 public static function replacePseudoconstant($options, $value, $reverse = FALSE) {
224 $matches = [];
225 foreach ((array) $value as $val) {
226 if (!$reverse && isset($options[$val])) {
227 $matches[] = $options[$val];
228 }
229 elseif ($reverse && array_search($val, $options) !== FALSE) {
230 $matches[] = array_search($val, $options);
231 }
232 }
233 return is_array($value) ? $matches : $matches[0] ?? NULL;
234 }
235
236 /**
237 * @param mixed $value
238 * @param string $dataType
239 * @return mixed
240 */
241 public static function convertDataType($value, $dataType) {
242 if (isset($value) && $dataType) {
243 if (is_array($value)) {
244 foreach ($value as $key => $val) {
245 $value[$key] = self::convertDataType($val, $dataType);
246 }
247 return $value;
248 }
249
250 switch ($dataType) {
251 case 'Boolean':
252 return (bool) $value;
253
254 case 'Integer':
255 return (int) $value;
256
257 case 'Money':
258 case 'Float':
259 return (float) $value;
260 }
261 }
262 return $value;
263 }
264
265 /**
266 * Lists all field names (including suffixed variants) that should be removed for a given contact type.
267 *
268 * @param string $contactType
269 * Individual|Organization|Household
270 * @param string $prefix
271 * Path at which these fields are found, e.g. "address.contact."
272 * @return array
273 */
274 public static function contactFieldsToRemove($contactType, $prefix) {
275 if (!isset(\Civi::$statics[__CLASS__][__FUNCTION__][$contactType])) {
276 \Civi::$statics[__CLASS__][__FUNCTION__][$contactType] = [];
277 foreach (\CRM_Contact_DAO_Contact::fields() as $field) {
278 if (!empty($field['contactType']) && $field['contactType'] != $contactType) {
279 \Civi::$statics[__CLASS__][__FUNCTION__][$contactType][] = $field['name'];
280 // Include suffixed variants like prefix_id:label
281 if (!empty($field['pseudoconstant'])) {
282 foreach (array_keys(self::$pseudoConstantContexts) as $suffix) {
283 \Civi::$statics[__CLASS__][__FUNCTION__][$contactType][] = $field['name'] . ':' . $suffix;
284 }
285 }
286 }
287 }
288 }
289 // Add prefix paths
290 return array_map(function($name) use ($prefix) {
291 return $prefix . $name;
292 }, \Civi::$statics[__CLASS__][__FUNCTION__][$contactType]);
293 }
294
295 }