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',
34 public static $pseudoConstantSuffixes = ['name', 'abbr', 'label', 'color', 'description', 'icon'];
37 * Massage values into the format the BAO expects for a write operation
39 * @param array $params
40 * @param array $fields
41 * @throws \API_Exception
43 public static function formatWriteParams(&$params, $fields) {
44 foreach ($fields as $name => $field) {
45 if (!empty($params[$name])) {
46 $value =& $params[$name];
47 // Hack for null values -- see comment below
48 if ($value === 'null') {
51 self
::formatInputValue($value, $name, $field, 'create');
52 // Ensure we have an array for serialized fields
53 if (!empty($field['serialize'] && !is_array($value))) {
54 $value = (array) $value;
58 * Because of the wacky way that database values are saved we need to format
59 * some of the values here. In this strange world the string 'null' is used to
60 * unset values. Hence if we encounter true null we change it to string 'null'.
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) {
70 $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 $fieldName
84 * @param array $fieldSpec
85 * @param string $action
86 * @throws \API_Exception
87 * @throws \CRM_Core_Exception
89 public static function formatInputValue(&$value, $fieldName, $fieldSpec, $action = 'get') {
90 // Evaluate pseudoconstant suffix
91 $suffix = strpos($fieldName, ':');
93 $options = self
::getPseudoconstantList($fieldSpec['entity'], $fieldSpec['name'], substr($fieldName, $suffix +
1), $action);
94 $value = self
::replacePseudoconstant($options, $value, TRUE);
97 elseif (is_array($value)) {
98 foreach ($value as &$val) {
99 self
::formatInputValue($val, $fieldName, $fieldSpec, $action);
103 $fk = $fieldSpec['name'] == 'id' ?
$fieldSpec['entity'] : $fieldSpec['fk_entity'] ??
NULL;
105 if ($fk === 'Domain' && $value === 'current_domain') {
106 $value = \CRM_Core_Config
::domainID();
109 if ($fk === 'Contact' && !is_numeric($value)) {
110 $value = \
_civicrm_api3_resolve_contactID($value);
111 if ('unknown-user' === $value) {
112 throw new \
API_Exception("\"{$fieldSpec['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $fieldSpec['name'], "type" => "integer"]);
116 switch ($fieldSpec['data_type'] ??
NULL) {
118 $value = date('Y-m-d H:i:s', strtotime($value));
122 $value = date('Ymd', strtotime($value));
126 $hic = \CRM_Utils_API_HTMLInputCoder
::singleton();
127 if (!$hic->isSkippedField($fieldSpec['name'])) {
128 $value = $hic->encodeValue($value);
133 * Unserialize raw DAO values and convert to correct type
135 * @param array $results
136 * @param array $fields
137 * @param string $entity
138 * @param string $action
139 * @throws \API_Exception
140 * @throws \CRM_Core_Exception
142 public static function formatOutputValues(&$results, $fields, $entity, $action = 'get') {
144 foreach ($results as &$result) {
145 $contactTypePaths = [];
146 foreach ($result as $fieldExpr => $value) {
147 $field = $fields[$fieldExpr] ??
NULL;
148 $dataType = $field['data_type'] ??
($fieldExpr == 'id' ?
'Integer' : NULL);
150 // Evaluate pseudoconstant suffixes
151 $suffix = strrpos($fieldExpr, ':');
153 $fieldName = empty($field['custom_field_id']) ?
$field['name'] : 'custom_' . $field['custom_field_id'];
154 $fieldOptions[$fieldExpr] = $fieldOptions[$fieldExpr] ?? self
::getPseudoconstantList($field['entity'], $fieldName, substr($fieldExpr, $suffix +
1), $result, $action);
157 if (!empty($field['serialize'])) {
158 if (is_string($value)) {
159 $value = \CRM_Core_DAO
::unSerializeField($value, $field['serialize']);
162 if (isset($fieldOptions[$fieldExpr])) {
163 $value = self
::replacePseudoconstant($fieldOptions[$fieldExpr], $value);
165 // Keep track of contact types for self::contactFieldsToRemove
166 if ($value && isset($field['entity']) && $field['entity'] === 'Contact' && $field['name'] === 'contact_type') {
167 $prefix = strrpos($fieldExpr, '.');
168 $contactTypePaths[$prefix ?
substr($fieldExpr, 0, $prefix +
1) : ''] = $value;
171 $result[$fieldExpr] = self
::convertDataType($value, $dataType);
173 // Remove inapplicable contact fields
174 foreach ($contactTypePaths as $prefix => $contactType) {
175 \CRM_Utils_Array
::remove($result, self
::contactFieldsToRemove($contactType, $prefix));
181 * Retrieves pseudoconstant option list for a field.
183 * @param string $entity
185 * @param string $fieldName
186 * @param string $valueType
187 * name|label|abbr from self::$pseudoConstantContexts
188 * @param array $params
189 * Other values for this object
190 * @param string $action
192 * @throws \API_Exception
194 public static function getPseudoconstantList($entity, $fieldName, $valueType, $params = [], $action = 'get') {
195 $context = self
::$pseudoConstantContexts[$valueType] ??
NULL;
196 // For create actions, only unique identifiers can be used.
197 // For get actions any valid suffix is ok.
198 if (($action === 'create' && !$context) ||
!in_array($valueType, self
::$pseudoConstantSuffixes, TRUE)) {
199 throw new \
API_Exception('Illegal expression');
201 $baoName = $context ? CoreUtil
::getBAOFromApiName($entity) : NULL;
202 // Use BAO::buildOptions if possible
204 $options = $baoName::buildOptions($fieldName, $context, $params);
206 // Fallback for option lists that exist in the api but not the BAO
207 if (!isset($options) ||
$options === FALSE) {
208 $options = civicrm_api4($entity, 'getFields', ['action' => $action, 'loadOptions' => ['id', $valueType], 'where' => [['name', '=', $fieldName]]])[0]['options'] ??
NULL;
209 $options = $options ?
array_column($options, $valueType, 'id') : $options;
211 if (is_array($options)) {
214 throw new \
API_Exception("No option list found for '$fieldName'");
218 * Replaces value (or an array of values) with options from a pseudoconstant list.
220 * The direction of lookup defaults to transforming ids to option values for api output;
221 * for api input, set $reverse = TRUE to transform option values to ids.
223 * @param array $options
224 * @param string|string[] $value
225 * @param bool $reverse
226 * Is this a reverse lookup (for transforming input instead of output)
227 * @return array|mixed|null
229 public static function replacePseudoconstant($options, $value, $reverse = FALSE) {
231 foreach ((array) $value as $val) {
232 if (!$reverse && isset($options[$val])) {
233 $matches[] = $options[$val];
235 elseif ($reverse && array_search($val, $options) !== FALSE) {
236 $matches[] = array_search($val, $options);
239 return is_array($value) ?
$matches : $matches[0] ??
NULL;
243 * @param mixed $value
244 * @param string $dataType
247 public static function convertDataType($value, $dataType) {
248 if (isset($value) && $dataType) {
249 if (is_array($value)) {
250 foreach ($value as $key => $val) {
251 $value[$key] = self
::convertDataType($val, $dataType);
258 return (bool) $value;
265 return (float) $value;
272 * Lists all field names (including suffixed variants) that should be removed for a given contact type.
274 * @param string $contactType
275 * Individual|Organization|Household
276 * @param string $prefix
277 * Path at which these fields are found, e.g. "address.contact."
280 public static function contactFieldsToRemove($contactType, $prefix) {
281 if (!isset(\Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType])) {
282 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType] = [];
283 foreach (\CRM_Contact_DAO_Contact
::fields() as $field) {
284 if (!empty($field['contactType']) && $field['contactType'] != $contactType) {
285 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType][] = $field['name'];
286 // Include suffixed variants like prefix_id:label
287 if (!empty($field['pseudoconstant'])) {
288 foreach (self
::$pseudoConstantSuffixes as $suffix) {
289 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType][] = $field['name'] . ':' . $suffix;
296 return array_map(function($name) use ($prefix) {
297 return $prefix . $name;
298 }, \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType]);