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
20 namespace Civi\Api4\Utils
;
22 require_once 'api/v3/utils.php';
24 class FormattingUtil
{
26 public static $pseudoConstantContexts = [
28 'abbr' => 'abbreviate',
32 public static $pseudoConstantSuffixes = ['name', 'abbr', 'label', 'color', 'description', 'icon'];
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, 'create');
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 * @param string $action
84 * @throws \API_Exception
85 * @throws \CRM_Core_Exception
87 public static function formatInputValue(&$value, $fieldName, $fieldSpec, $action = 'get') {
88 // Evaluate pseudoconstant suffix
89 $suffix = strpos($fieldName, ':');
91 $options = self
::getPseudoconstantList($fieldSpec['entity'], $fieldSpec['name'], substr($fieldName, $suffix +
1), $action);
92 $value = self
::replacePseudoconstant($options, $value, TRUE);
95 elseif (is_array($value)) {
96 foreach ($value as &$val) {
97 self
::formatInputValue($val, $fieldName, $fieldSpec, $action);
101 $fk = $fieldSpec['name'] == 'id' ?
$fieldSpec['entity'] : $fieldSpec['fk_entity'] ??
NULL;
103 if ($fk === 'Domain' && $value === 'current_domain') {
104 $value = \CRM_Core_Config
::domainID();
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"]);
114 switch ($fieldSpec['data_type'] ??
NULL) {
116 $value = date('Y-m-d H:i:s', strtotime($value));
120 $value = date('Ymd', strtotime($value));
124 $hic = \CRM_Utils_API_HTMLInputCoder
::singleton();
125 if (!$hic->isSkippedField($fieldSpec['name'])) {
126 $value = $hic->encodeValue($value);
131 * Unserialize raw DAO values and convert to correct type
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
140 public static function formatOutputValues(&$results, $fields, $entity, $action = 'get') {
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);
148 // Evaluate pseudoconstant suffixes
149 $suffix = strrpos($fieldExpr, ':');
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);
155 if (!empty($field['serialize'])) {
156 if (is_string($value)) {
157 $value = \CRM_Core_DAO
::unSerializeField($value, $field['serialize']);
160 if (isset($fieldOptions[$fieldExpr])) {
161 $value = self
::replacePseudoconstant($fieldOptions[$fieldExpr], $value);
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;
169 $result[$fieldExpr] = self
::convertDataType($value, $dataType);
171 // Remove inapplicable contact fields
172 foreach ($contactTypePaths as $prefix => $contactType) {
173 \CRM_Utils_Array
::remove($result, self
::contactFieldsToRemove($contactType, $prefix));
179 * Retrieves pseudoconstant option list for a field.
181 * @param string $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
190 * @throws \API_Exception
192 public static function getPseudoconstantList($entity, $fieldName, $valueType, $params = [], $action = 'get') {
193 $context = self
::$pseudoConstantContexts[$valueType] ??
NULL;
194 // For create actions, only unique identifiers can be used.
195 // For get actions any valid suffix is ok.
196 if (($action === 'create' && !$context) ||
!in_array($valueType, self
::$pseudoConstantSuffixes, TRUE)) {
197 throw new \
API_Exception('Illegal expression');
199 $baoName = $context ? CoreUtil
::getBAOFromApiName($entity) : NULL;
200 // Use BAO::buildOptions if possible
202 $options = $baoName::buildOptions($fieldName, $context, $params);
204 // Fallback for option lists that exist in the api but not the BAO
205 if (!isset($options) ||
$options === FALSE) {
206 $options = civicrm_api4($entity, 'getFields', ['action' => $action, 'loadOptions' => ['id', $valueType], 'where' => [['name', '=', $fieldName]]])[0]['options'] ??
NULL;
207 $options = $options ?
array_column($options, $valueType, 'id') : $options;
209 if (is_array($options)) {
212 throw new \
API_Exception("No option list found for '$fieldName'");
216 * Replaces value (or an array of values) with options from a pseudoconstant list.
218 * The direction of lookup defaults to transforming ids to option values for api output;
219 * for api input, set $reverse = TRUE to transform option values to ids.
221 * @param array $options
222 * @param string|string[] $value
223 * @param bool $reverse
224 * Is this a reverse lookup (for transforming input instead of output)
225 * @return array|mixed|null
227 public static function replacePseudoconstant($options, $value, $reverse = FALSE) {
229 foreach ((array) $value as $val) {
230 if (!$reverse && isset($options[$val])) {
231 $matches[] = $options[$val];
233 elseif ($reverse && array_search($val, $options) !== FALSE) {
234 $matches[] = array_search($val, $options);
237 return is_array($value) ?
$matches : $matches[0] ??
NULL;
241 * @param mixed $value
242 * @param string $dataType
245 public static function convertDataType($value, $dataType) {
246 if (isset($value) && $dataType) {
247 if (is_array($value)) {
248 foreach ($value as $key => $val) {
249 $value[$key] = self
::convertDataType($val, $dataType);
256 return (bool) $value;
263 return (float) $value;
270 * Lists all field names (including suffixed variants) that should be removed for a given contact type.
272 * @param string $contactType
273 * Individual|Organization|Household
274 * @param string $prefix
275 * Path at which these fields are found, e.g. "address.contact."
278 public static function contactFieldsToRemove($contactType, $prefix) {
279 if (!isset(\Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType])) {
280 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType] = [];
281 foreach (\CRM_Contact_DAO_Contact
::fields() as $field) {
282 if (!empty($field['contactType']) && $field['contactType'] != $contactType) {
283 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType][] = $field['name'];
284 // Include suffixed variants like prefix_id:label
285 if (!empty($field['pseudoconstant'])) {
286 foreach (self
::$pseudoConstantSuffixes as $suffix) {
287 \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType][] = $field['name'] . ':' . $suffix;
294 return array_map(function($name) use ($prefix) {
295 return $prefix . $name;
296 }, \Civi
::$statics[__CLASS__
][__FUNCTION__
][$contactType]);