4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 namespace Civi\Api4\Utils
;
15 use Civi\Api4\Query\SqlExpression
;
17 require_once 'api/v3/utils.php';
19 class FormattingUtil
{
24 public static $pseudoConstantContexts = [
26 'abbr' => 'abbreviate',
33 public static $pseudoConstantSuffixes = ['name', 'abbr', 'label', 'color', 'description', 'icon', 'grouping'];
36 * Massage values into the format the BAO expects for a write operation
38 * @param array $params
39 * @param array $fields
40 * @throws \API_Exception
42 public static function formatWriteParams(&$params, $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') {
50 self
::formatInputValue($value, $name, $field);
51 // Ensure we have an array for serialized fields
52 if (!empty($field['serialize'] && !is_array($value))) {
53 $value = (array) $value;
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. If we encounter true null at this layer we change it to an empty string
60 * and it will be converted to 'null' by CRM_Core_DAO::copyValues.
62 * If we encounter the string 'null' then we assume the user actually wants to
63 * set the value to string null. However since the string null is reserved for
64 * unsetting values we must change it. Another quirk of the DB_DataObject is
65 * that it allows 'Null' to be set, but any other variation of string 'null'
66 * will be converted to true null, e.g. 'nuLL', 'NUlL' etc. so we change it to
69 elseif (array_key_exists($name, $params) && $params[$name] === NULL) {
74 \CRM_Utils_API_HTMLInputCoder
::singleton()->encodeRow($params);
78 * Transform raw api input to appropriate format for use in a SQL query.
80 * This is used by read AND write actions (Get, Create, Update, Replace)
83 * @param string|null $fieldName
84 * @param array $fieldSpec
85 * @param string|null $operator (only for 'get' actions)
86 * @param null $index (for recursive loops)
87 * @throws \API_Exception
88 * @throws \CRM_Core_Exception
90 public static function formatInputValue(&$value, ?
string $fieldName, array $fieldSpec, &$operator = NULL, $index = NULL) {
91 // Evaluate pseudoconstant suffix
92 $suffix = strpos(($fieldName ??
''), ':');
94 $options = self
::getPseudoconstantList($fieldSpec, $fieldName, [], $operator ?
'get' : 'create');
95 $value = self
::replacePseudoconstant($options, $value, TRUE);
98 elseif (is_array($value)) {
100 foreach ($value as &$val) {
101 self
::formatInputValue($val, $fieldName, $fieldSpec, $operator, $i++
);
105 $fk = $fieldSpec['name'] == 'id' ?
$fieldSpec['entity'] : $fieldSpec['fk_entity'] ??
NULL;
107 if ($fk === 'Domain' && $value === 'current_domain') {
108 $value = \CRM_Core_Config
::domainID();
111 if ($fk === 'Contact' && !is_numeric($value)) {
112 $value = \
_civicrm_api3_resolve_contactID($value);
113 if ('unknown-user' === $value) {
114 throw new \
API_Exception("\"{$fieldSpec['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldSpec['name'], "type" => "integer"]);
118 switch ($fieldSpec['data_type'] ??
NULL) {
120 $value = self
::formatDateValue('YmdHis', $value, $operator, $index);
124 $value = self
::formatDateValue('Ymd', $value, $operator, $index);
128 $hic = \CRM_Utils_API_HTMLInputCoder
::singleton();
129 if (is_string($value) && $fieldName && !$hic->isSkippedField($fieldSpec['name'])) {
130 $value = $hic->encodeValue($value);
135 * Parse date expressions.
137 * Expands relative date range expressions, modifying the sql operator if necessary
143 * @return array|string
145 public static function formatDateValue($format, $value, &$operator = NULL, $index = NULL) {
146 // Non-relative dates (or if no search operator)
147 if (!$operator ||
!array_key_exists($value, \CRM_Core_OptionGroup
::values('relative_date_filters'))) {
148 return date($format, strtotime($value ??
''));
150 if (isset($index) && !strstr($operator, 'BETWEEN')) {
151 throw new \
API_Exception("Relative dates cannot be in an array using the $operator operator.");
153 [$dateFrom, $dateTo] = \CRM_Utils_Date
::getFromTo($value);
155 // Convert relative date filters to use BETWEEN/NOT BETWEEN operator
161 $operator = ($operator === '=' ||
$operator === 'LIKE') ?
'BETWEEN' : 'NOT BETWEEN';
162 return [self
::formatDateValue($format, $dateFrom), self
::formatDateValue($format, $dateTo)];
164 // Less-than or greater-than-equal-to comparisons use the lower value
167 return self
::formatDateValue($format, $dateFrom);
169 // Greater-than or less-than-equal-to comparisons use the higher value
172 return self
::formatDateValue($format, $dateTo);
174 // For BETWEEN expressions, we are already inside a loop of the 2 values, so give the lower value if index=0, higher value if index=1
177 return self
::formatDateValue($format, $index ?
$dateTo : $dateFrom);
180 throw new \
API_Exception("Relative dates cannot be used with the $operator operator.");
185 * Unserialize raw DAO values and convert to correct type
187 * @param array $results
188 * @param array $fields
189 * @param string $action
190 * @param array $selectAliases
191 * @throws \API_Exception
192 * @throws \CRM_Core_Exception
194 public static function formatOutputValues(&$results, $fields, $action = 'get', $selectAliases = []) {
195 foreach ($results as &$result) {
196 $contactTypePaths = [];
197 foreach ($result as $key => $value) {
198 $fieldExpr = SqlExpression
::convert($selectAliases[$key] ??
$key);
199 $fieldName = \CRM_Utils_Array
::first($fieldExpr->getFields() ??
'');
200 $baseName = $fieldName ? \CRM_Utils_Array
::first(explode(':', $fieldName)) : NULL;
201 $field = $fields[$fieldName] ??
$fields[$baseName] ??
NULL;
202 $dataType = $field['data_type'] ??
($fieldName == 'id' ?
'Integer' : NULL);
203 // Allow Sql Functions to do special formatting and/or alter the $dataType
204 if (method_exists($fieldExpr, 'formatOutputValue') && is_string($value)) {
205 $result[$key] = $value = $fieldExpr->formatOutputValue($value, $dataType);
207 if (!empty($field['output_formatters'])) {
208 self
::applyFormatters($result, $fieldName, $field, $value);
211 // Evaluate pseudoconstant suffixes
212 $suffix = strrpos(($fieldName ??
''), ':');
213 $fieldOptions = NULL;
215 $fieldOptions = self
::getPseudoconstantList($field, $fieldName, $result, $action);
218 if ($fieldExpr->supportsExpansion
) {
219 if (!empty($field['serialize']) && is_string($value)) {
220 $value = \CRM_Core_DAO
::unSerializeField($value, $field['serialize']);
222 if (isset($fieldOptions)) {
223 $value = self
::replacePseudoconstant($fieldOptions, $value);
226 // Keep track of contact types for self::contactFieldsToRemove
227 if ($value && isset($field['entity']) && $field['entity'] === 'Contact' && $field['name'] === 'contact_type') {
228 $prefix = strrpos($fieldName, '.');
229 $contactTypePaths[$prefix ?
substr($fieldName, 0, $prefix +
1) : ''] = $value;
231 $result[$key] = self
::convertDataType($value, $dataType);
233 // Remove inapplicable contact fields
234 foreach ($contactTypePaths as $prefix => $contactType) {
235 \CRM_Utils_Array
::remove($result, self
::contactFieldsToRemove($contactType, $prefix));
241 * Retrieves pseudoconstant option list for a field.
243 * @param array $field
244 * @param string $fieldAlias
245 * Field path plus pseudoconstant suffix, e.g. 'contact.employer_id.contact_sub_type:label'
246 * @param array $params
247 * Other values for this object
248 * @param string $action
250 * @throws \API_Exception
252 public static function getPseudoconstantList(array $field, string $fieldAlias, $params = [], $action = 'get') {
253 [$fieldPath, $valueType] = explode(':', $fieldAlias);
254 $context = self
::$pseudoConstantContexts[$valueType] ??
NULL;
255 // For create actions, only unique identifiers can be used.
256 // For get actions any valid suffix is ok.
257 if (($action === 'create' && !$context) ||
!in_array($valueType, self
::$pseudoConstantSuffixes, TRUE)) {
258 throw new \
API_Exception('Illegal expression');
260 $baoName = $context ? CoreUtil
::getBAOFromApiName($field['entity']) : NULL;
261 // Use BAO::buildOptions if possible
263 $fieldName = empty($field['custom_field_id']) ?
$field['name'] : 'custom_' . $field['custom_field_id'];
264 $options = $baoName::buildOptions($fieldName, $context, self
::filterByPrefix($params, $fieldPath, $field['name']));
266 // Fallback for option lists that exist in the api but not the BAO
267 if (!isset($options) ||
$options === FALSE) {
268 $options = civicrm_api4($field['entity'], 'getFields', ['action' => $action, 'loadOptions' => ['id', $valueType], 'where' => [['name', '=', $field['name']]]])[0]['options'] ??
NULL;
269 $options = $options ?
array_column($options, $valueType, 'id') : $options;
271 if (is_array($options)) {
274 throw new \
API_Exception("No option list found for '{$field['name']}'");
278 * Replaces value (or an array of values) with options from a pseudoconstant list.
280 * The direction of lookup defaults to transforming ids to option values for api output;
281 * for api input, set $reverse = TRUE to transform option values to ids.
283 * @param array $options
284 * @param string|string[] $value
285 * @param bool $reverse
286 * Is this a reverse lookup (for transforming input instead of output)
287 * @return array|mixed|null
289 public static function replacePseudoconstant($options, $value, $reverse = FALSE) {
291 foreach ((array) $value as $val) {
292 if (!$reverse && isset($options[$val])) {
293 $matches[] = $options[$val];
295 elseif ($reverse && array_search($val, $options) !== FALSE) {
296 $matches[] = array_search($val, $options);
299 return is_array($value) ?
$matches : $matches[0] ??
NULL;
303 * Apply a field's output_formatters callback functions
305 * @param array $result
306 * @param string $fieldPath
307 * @param array $field
308 * @param mixed $value
310 private static function applyFormatters(array $result, string $fieldPath, array $field, &$value) {
311 $row = self
::filterByPrefix($result, $fieldPath, $field['name']);
313 foreach ($field['output_formatters'] as $formatter) {
314 $formatter($value, $row, $field);
319 * @param mixed $value
320 * @param string $dataType
323 public static function convertDataType($value, $dataType) {
324 if (isset($value) && $dataType) {
325 if (is_array($value)) {
326 foreach ($value as $key => $val) {
327 $value[$key] = self
::convertDataType($val, $dataType);
334 return (bool) $value;
341 return (float) $value;
344 // Strip time from date-only fields
345 return substr($value, 0, 10);
352 * Lists all field names (including suffixed variants) that should be removed for a given contact type.
354 * @param string $contactType
355 * Individual|Organization|Household
356 * @param string $prefix
357 * Path at which these fields are found, e.g. "address.contact."
360 public static function contactFieldsToRemove($contactType, $prefix) {
361 if (!isset(\Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType])) {
362 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType] = [];
363 foreach (\CRM_Contact_DAO_Contact
::fields() as $field) {
364 if (!empty($field['contactType']) && $field['contactType'] != $contactType) {
365 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType][] = $field['name'];
366 // Include suffixed variants like prefix_id:label
367 if (!empty($field['pseudoconstant'])) {
368 foreach (self
::$pseudoConstantSuffixes as $suffix) {
369 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType][] = $field['name'] . ':' . $suffix;
376 return array_map(function($name) use ($prefix) {
377 return $prefix . $name;
378 }, \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType]);
382 * Given a field belonging to either the main entity or a joined entity,
383 * and a values array of [path => value], this returns all values which share the same root path.
385 * Works by filtering array keys to only include those with the same prefix as a given field,
386 * stripping them of that prefix.
391 * 'first_name' => 'a',
392 * 'middle_name' => 'b',
393 * 'related_contact.first_name' => 'c',
394 * 'related_contact.last_name' => 'd',
395 * 'activity.subject' => 'e',
397 * $fieldPath = 'related_contact.id'
400 * filterByPrefix($values, $fieldPath, $fieldName)
402 * 'first_name' => 'c',
403 * 'last_name' => 'd',
407 * @param array $values
408 * @param string $fieldPath
409 * @param string $fieldName
412 public static function filterByPrefix(array $values, string $fieldPath, string $fieldName): array {
414 $prefix = substr($fieldPath, 0, strpos($fieldPath, $fieldName));
415 foreach ($values as $key => $val) {
416 if (!$prefix ||
strpos($key, $prefix) === 0) {
417 $filtered[substr($key, strlen($prefix))] = $val;