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 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
22 namespace Civi\Api4\Utils
;
24 require_once 'api/v3/utils.php';
26 class FormattingUtil
{
28 public static $pseudoConstantContexts = [
30 'abbr' => 'abbreviate',
35 * Massage values into the format the BAO expects for a write operation
37 * @param array $params
38 * @param array $fields
39 * @throws \API_Exception
41 public static function formatWriteParams(&$params, $fields) {
42 foreach ($fields as $name => $field) {
43 if (!empty($params[$name])) {
44 $value =& $params[$name];
45 // Hack for null values -- see comment below
46 if ($value === 'null') {
49 self
::formatInputValue($value, $name, $field);
50 // Ensure we have an array for serialized fields
51 if (!empty($field['serialize'] && !is_array($value))) {
52 $value = (array) $value;
56 * Because of the wacky way that database values are saved we need to format
57 * some of the values here. In this strange world the string 'null' is used to
58 * unset values. Hence if we encounter true null we change it to string 'null'.
60 * If we encounter the string 'null' then we assume the user actually wants to
61 * set the value to string null. However since the string null is reserved for
62 * unsetting values we must change it. Another quirk of the DB_DataObject is
63 * that it allows 'Null' to be set, but any other variation of string 'null'
64 * will be converted to true null, e.g. 'nuLL', 'NUlL' etc. so we change it to
67 elseif (array_key_exists($name, $params) && $params[$name] === NULL) {
68 $params[$name] = 'null';
72 \CRM_Utils_API_HTMLInputCoder
::singleton()->encodeRow($params);
76 * Transform raw api input to appropriate format for use in a SQL query.
78 * This is used by read AND write actions (Get, Create, Update, Replace)
81 * @param string $fieldName
82 * @param array $fieldSpec
83 * @throws \API_Exception
85 public static function formatInputValue(&$value, $fieldName, $fieldSpec) {
86 // Evaluate pseudoconstant suffix
87 $suffix = strpos($fieldName, ':');
89 $options = self
::getPseudoconstantList($fieldSpec['entity'], $fieldSpec['name'], substr($fieldName, $suffix +
1));
90 $value = self
::replacePseudoconstant($options, $value, TRUE);
93 elseif (is_array($value)) {
94 foreach ($value as &$val) {
95 self
::formatInputValue($val, $fieldName, $fieldSpec);
99 $fk = $fieldSpec['name'] == 'id' ?
$fieldSpec['entity'] : $fieldSpec['fk_entity'] ??
NULL;
101 if ($fk === 'Domain' && $value === 'current_domain') {
102 $value = \CRM_Core_Config
::domainID();
105 if ($fk === 'Contact' && !is_numeric($value)) {
106 $value = \
_civicrm_api3_resolve_contactID($value);
107 if ('unknown-user' === $value) {
108 throw new \
API_Exception("\"{$fieldSpec['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldSpec['name'], "type" => "integer"]);
112 switch ($fieldSpec['data_type'] ??
NULL) {
114 $value = date('Y-m-d H:i:s', strtotime($value));
118 $value = date('Ymd', strtotime($value));
122 $hic = \CRM_Utils_API_HTMLInputCoder
::singleton();
123 if (!$hic->isSkippedField($fieldSpec['name'])) {
124 $value = $hic->encodeValue($value);
129 * Unserialize raw DAO values and convert to correct type
131 * @param array $results
132 * @param array $fields
133 * @param string $entity
134 * @param string $action
135 * @throws \API_Exception
136 * @throws \CRM_Core_Exception
138 public static function formatOutputValues(&$results, $fields, $entity, $action = 'get') {
140 foreach ($results as &$result) {
141 $contactTypePaths = [];
142 foreach ($result as $fieldExpr => $value) {
143 $field = $fields[$fieldExpr] ??
NULL;
144 $dataType = $field['data_type'] ??
($fieldExpr == 'id' ?
'Integer' : NULL);
146 // Evaluate pseudoconstant suffixes
147 $suffix = strrpos($fieldExpr, ':');
149 $fieldName = empty($field['custom_field_id']) ?
$field['name'] : 'custom_' . $field['custom_field_id'];
150 $fieldOptions[$fieldExpr] = $fieldOptions[$fieldExpr] ?? self
::getPseudoconstantList($field['entity'], $fieldName, substr($fieldExpr, $suffix +
1), $result, $action);
153 if (!empty($field['serialize'])) {
154 if (is_string($value)) {
155 $value = \CRM_Core_DAO
::unSerializeField($value, $field['serialize']);
158 if (isset($fieldOptions[$fieldExpr])) {
159 $value = self
::replacePseudoconstant($fieldOptions[$fieldExpr], $value);
161 // Keep track of contact types for self::contactFieldsToRemove
162 if ($value && isset($field['entity']) && $field['entity'] === 'Contact' && $field['name'] === 'contact_type') {
163 $prefix = strrpos($fieldExpr, '.');
164 $contactTypePaths[$prefix ?
substr($fieldExpr, 0, $prefix +
1) : ''] = $value;
167 $result[$fieldExpr] = self
::convertDataType($value, $dataType);
169 // Remove inapplicable contact fields
170 foreach ($contactTypePaths as $prefix => $contactType) {
171 \CRM_Utils_Array
::remove($result, self
::contactFieldsToRemove($contactType, $prefix));
177 * Retrieves pseudoconstant option list for a field.
179 * @param string $entity
181 * @param string $fieldName
182 * @param string $valueType
183 * name|label|abbr from self::$pseudoConstantContexts
184 * @param array $params
185 * Other values for this object
186 * @param string $action
188 * @throws \API_Exception
190 public static function getPseudoconstantList($entity, $fieldName, $valueType, $params = [], $action = 'get') {
191 $context = self
::$pseudoConstantContexts[$valueType] ??
NULL;
193 throw new \
API_Exception('Illegal expression');
195 $baoName = CoreUtil
::getBAOFromApiName($entity);
196 // Use BAO::buildOptions if possible
198 $options = $baoName::buildOptions($fieldName, $context, $params);
200 // Fallback for option lists that exist in the api but not the BAO - note: $valueType gets ignored here
201 if (!isset($options) ||
$options === FALSE) {
202 $options = civicrm_api4($entity, 'getFields', ['action' => $action, 'loadOptions' => TRUE, 'where' => [['name', '=', $fieldName]]])[0]['options'] ??
NULL;
204 if (is_array($options)) {
207 throw new \
API_Exception("No option list found for '$fieldName'");
211 * Replaces value (or an array of values) with options from a pseudoconstant list.
213 * The direction of lookup defaults to transforming ids to option values for api output;
214 * for api input, set $reverse = TRUE to transform option values to ids.
216 * @param array $options
217 * @param string|string[] $value
218 * @param bool $reverse
219 * Is this a reverse lookup (for transforming input instead of output)
220 * @return array|mixed|null
222 public static function replacePseudoconstant($options, $value, $reverse = FALSE) {
224 foreach ((array) $value as $val) {
225 if (!$reverse && isset($options[$val])) {
226 $matches[] = $options[$val];
228 elseif ($reverse && array_search($val, $options) !== FALSE) {
229 $matches[] = array_search($val, $options);
232 return is_array($value) ?
$matches : $matches[0] ??
NULL;
236 * @param mixed $value
237 * @param string $dataType
240 public static function convertDataType($value, $dataType) {
241 if (isset($value) && $dataType) {
242 if (is_array($value)) {
243 foreach ($value as $key => $val) {
244 $value[$key] = self
::convertDataType($val, $dataType);
251 return (bool) $value;
258 return (float) $value;
265 * Lists all field names (including suffixed variants) that should be removed for a given contact type.
267 * @param string $contactType
268 * Individual|Organization|Household
269 * @param string $prefix
270 * Path at which these fields are found, e.g. "address.contact."
273 public static function contactFieldsToRemove($contactType, $prefix) {
274 if (!isset(\Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType])) {
275 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType] = [];
276 foreach (\CRM_Contact_DAO_Contact
::fields() as $field) {
277 if (!empty($field['contactType']) && $field['contactType'] != $contactType) {
278 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType][] = $field['name'];
279 // Include suffixed variants like prefix_id:label
280 if (!empty($field['pseudoconstant'])) {
281 foreach (array_keys(self
::$pseudoConstantContexts) as $suffix) {
282 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType][] = $field['name'] . ':' . $suffix;
289 return array_map(function($name) use ($prefix) {
290 return $prefix . $name;
291 }, \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType]);