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\Generic\Traits
;
15 use Civi\Api4\CustomField
;
16 use Civi\Api4\Service\Schema\Joinable\CustomGroupJoinable
;
17 use Civi\Api4\Utils\FormattingUtil
;
18 use Civi\Api4\Utils\CoreUtil
;
19 use Civi\Api4\Utils\ReflectionUtils
;
22 * @method string getLanguage()
23 * @method $this setLanguage(string $language)
25 trait DAOActionTrait
{
28 * Specify the language to use if this is a multi-lingual environment.
30 * E.g. "en_US" or "fr_CA"
36 private $_maxWeights = [];
39 * @return \CRM_Core_DAO|string
41 protected function getBaoName() {
42 return CoreUtil
::getBAOFromApiName($this->getEntityName());
46 * Convert saved object to array
48 * Used by create, update & save actions
50 * @param \CRM_Core_DAO $bao
54 public function baoToArray($bao, $input) {
55 $allFields = array_column($bao->fields(), 'name');
56 if (!empty($this->reload
)) {
57 $inputFields = $allFields;
61 $inputFields = array_keys($input);
62 // Convert 'null' input to true null
63 foreach ($input as $key => $val) {
64 if ($val === 'null') {
70 foreach ($allFields as $field) {
71 if (isset($bao->$field) ||
in_array($field, $inputFields)) {
72 $values[$field] = $bao->$field ??
NULL;
79 * Fill field defaults which were declared by the api.
81 * Note: default values from core are ignored because the BAO or database layer will supply them.
83 * @param array $params
85 protected function fillDefaults(&$params) {
86 $fields = $this->entityFields();
87 $bao = $this->getBaoName();
88 $coreFields = array_column($bao::fields(), NULL, 'name');
90 foreach ($fields as $name => $field) {
91 // If a default value in the api field is different than in core, the api should override it.
92 if (!isset($params[$name]) && !empty($field['default_value']) && $field['default_value'] != \CRM_Utils_Array
::pathGet($coreFields, [$name, 'default'])) {
93 $params[$name] = $field['default_value'];
99 * Write bao objects as part of a create/update/save action.
101 * @param array $items
102 * The records to write to the DB.
105 * The records after being written to the DB (e.g. including newly assigned "id").
106 * @throws \API_Exception
107 * @throws \CRM_Core_Exception
109 protected function writeObjects($items) {
110 $updateWeights = FALSE;
111 // Adjust weights for sortable entities
112 if (in_array('SortableEntity', CoreUtil
::getInfoItem($this->getEntityName(), 'type'))) {
113 $weightField = CoreUtil
::getInfoItem($this->getEntityName(), 'order_by');
114 // Only take action if updating a single record, or if no weights are specified in any record
115 // This avoids messing up a bulk update with multiple recalculations
116 if (count($items) === 1 ||
!array_filter(array_column($items, $weightField))) {
117 $updateWeights = TRUE;
123 foreach ($items as &$item) {
124 $entityId = $item['id'] ??
NULL;
125 FormattingUtil
::formatWriteParams($item, $this->entityFields());
126 $this->formatCustomParams($item, $entityId);
128 // Adjust weights for sortable entities
129 if ($updateWeights) {
130 $this->updateWeight($item);
133 $item['check_permissions'] = $this->getCheckPermissions();
136 // Ensure array keys start at 0
137 $items = array_values($items);
139 foreach ($this->write($items) as $index => $dao) {
141 $errMessage = sprintf('%s write operation failed', $this->getEntityName());
142 throw new \
API_Exception($errMessage);
144 $result[] = $this->baoToArray($dao, $items[$index]);
147 \CRM_Utils_API_HTMLInputCoder
::singleton()->decodeRows($result);
148 FormattingUtil
::formatOutputValues($result, $this->entityFields());
153 * Overrideable function to save items using the appropriate BAO function
155 * @param array[] $items
156 * Items already formatted by self::writeObjects
157 * @return \CRM_Core_DAO[]
158 * Array of saved DAO records
160 protected function write(array $items) {
162 $baoName = $this->getBaoName();
164 $method = method_exists($baoName, 'create') ?
'create' : (method_exists($baoName, 'add') ?
'add' : NULL);
165 // Use BAO create or add method if not deprecated
166 if ($method && !ReflectionUtils
::isMethodDeprecated($baoName, $method)) {
167 foreach ($items as $item) {
168 $saved[] = $baoName::$method($item);
172 $saved = $baoName::writeRecords($items);
180 protected function formatWriteValues(&$record) {
181 $this->resolveFKValues($record);
182 parent
::formatWriteValues($record);
186 * Looks up an id based on some other property of an fk entity
188 * @param array $record
190 private function resolveFKValues(array &$record): void
{
191 // Resolve domain id first
192 uksort($record, function($a, $b) {
193 return substr($a, 0, 9) == 'domain_id' ?
-1 : 1;
195 foreach ($record as $key => $value) {
196 if (!$value ||
substr_count($key, '.') !== 1) {
199 [$fieldName, $fkField] = explode('.', $key);
200 $field = $this->entityFields()[$fieldName] ??
NULL;
201 if (!$field ||
empty($field['fk_entity'])) {
204 $fkDao = CoreUtil
::getBAOFromApiName($field['fk_entity']);
205 // Constrain search to the domain of the current entity
206 $domainConstraint = NULL;
207 if (isset($fkDao::getSupportedFields()['domain_id'])) {
208 if (!empty($record['domain_id'])) {
209 $domainConstraint = $record['domain_id'] === 'current_domain' ? \CRM_Core_Config
::domainID() : $record['domain_id'];
211 elseif (!empty($record['id']) && isset($this->entityFields()['domain_id'])) {
212 $domainConstraint = \CRM_Core_DAO
::getFieldValue($this->getBaoName(), $record['id'], 'domain_id');
215 if ($domainConstraint) {
216 $fkSearch = new $fkDao();
217 $fkSearch->domain_id
= $domainConstraint;
218 $fkSearch->$fkField = $value;
219 $fkSearch->find(TRUE);
220 $record[$fieldName] = $fkSearch->id
;
222 // Simple lookup without all the fuss about domains
224 $record[$fieldName] = \CRM_Core_DAO
::getFieldValue($fkDao, $value, 'id', $fkField);
226 unset($record[$key]);
231 * Converts params from flat array e.g. ['GroupName.Fieldname' => value] to the
232 * hierarchy expected by the BAO, nested within $params['custom'].
234 * @param array $params
235 * @param int $entityId
237 * @throws \API_Exception
238 * @throws \CRM_Core_Exception
240 protected function formatCustomParams(&$params, $entityId) {
243 foreach ($params as $name => $value) {
244 $field = $this->getCustomFieldInfo($name);
249 // Null and empty string are interchangeable as far as the custom bao understands
250 if (NULL === $value) {
254 if ($field['suffix']) {
255 $options = FormattingUtil
::getPseudoconstantList($field, $name, $params, $this->getActionName());
256 $value = FormattingUtil
::replacePseudoconstant($options, $value, TRUE);
259 if ($field['html_type'] === 'CheckBox') {
260 // this function should be part of a class
261 formatCheckBoxField($value, 'custom_' . $field['id'], $this->getEntityName());
264 // Match contact id to strings like "user_contact_id"
265 // FIXME handle arrays for multi-value contact reference fields, etc.
266 if ($field['data_type'] === 'ContactReference' && is_string($value) && !is_numeric($value)) {
267 // FIXME decouple from v3 API
268 require_once 'api/v3/utils.php';
269 $value = \
_civicrm_api3_resolve_contactID($value);
270 if ('unknown-user' === $value) {
271 throw new \
API_Exception("\"{$field['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $field['name'], "type" => "integer"]);
275 \CRM_Core_BAO_CustomField
::formatCustomField(
279 $field['custom_group_id.extends'],
280 // todo check when this is needed
284 $this->getCheckPermissions(),
289 $params['custom'] = $customParams ?
: NULL;
293 * Gets field info needed to save custom data
295 * @param string $fieldExpr
296 * Field identifier with possible suffix, e.g. MyCustomGroup.MyField1:label
297 * @return array{id: int, name: string, entity: string, suffix: string, html_type: string, data_type: string}|NULL
299 protected function getCustomFieldInfo(string $fieldExpr) {
300 if (strpos($fieldExpr, '.') === FALSE) {
303 [$groupName, $fieldName] = explode('.', $fieldExpr);
304 [$fieldName, $suffix] = array_pad(explode(':', $fieldName), 2, NULL);
305 $cacheKey = "APIv4_Custom_Fields-$groupName";
306 $info = \Civi
::cache('metadata')->get($cacheKey);
307 if (!isset($info[$fieldName])) {
309 $fields = CustomField
::get(FALSE)
310 ->addSelect('id', 'name', 'html_type', 'data_type', 'custom_group_id.extends')
311 ->addWhere('custom_group_id.name', '=', $groupName)
312 ->execute()->indexBy('name');
313 foreach ($fields as $name => $field) {
314 $field['custom_field_id'] = $field['id'];
315 $field['name'] = $groupName . '.' . $name;
316 $field['entity'] = CustomGroupJoinable
::getEntityFromExtends($field['custom_group_id.extends']);
317 $info[$name] = $field;
319 \Civi
::cache('metadata')->set($cacheKey, $info);
321 return isset($info[$fieldName]) ?
['suffix' => $suffix] +
$info[$fieldName] : NULL;
325 * Update weights when inserting or updating a sortable entity
326 * @param array $record
327 * @see SortableEntity
329 protected function updateWeight(array &$record) {
330 /** @var \CRM_Core_DAO|string $daoName */
331 $daoName = CoreUtil
::getInfoItem($this->getEntityName(), 'dao');
332 $weightField = CoreUtil
::getInfoItem($this->getEntityName(), 'order_by');
333 $idField = CoreUtil
::getIdFieldName($this->getEntityName());
334 // If updating an existing record without changing weight, do nothing
335 if (!isset($record[$weightField]) && !empty($record[$idField])) {
338 $daoFields = $daoName::getSupportedFields();
339 $newWeight = $record[$weightField] ??
NULL;
340 $oldWeight = empty($record[$idField]) ?
NULL : \CRM_Core_DAO
::getFieldValue($daoName, $record[$idField], $weightField);
342 // FIXME: Need a more metadata-ish approach. For now here's a hardcoded list of the fields sortable entities use for grouping.
343 $guesses = ['option_group_id', 'price_set_id', 'price_field_id', 'premiums_id', 'uf_group_id', 'custom_group_id', 'parent_id', 'domain_id'];
345 foreach (array_intersect($guesses, array_keys($daoFields)) as $filter) {
346 $filters[$filter] = $record[$filter] ??
(empty($record[$idField]) ?
NULL : \CRM_Core_DAO
::getFieldValue($daoName, $record[$idField], $filter));
348 // Supply default weight for new record
349 if (!isset($record[$weightField]) && empty($record[$idField])) {
350 $record[$weightField] = $this->getMaxWeight($daoName, $filters, $weightField);
353 $record[$weightField] = \CRM_Utils_Weight
::updateOtherWeights($daoName, $oldWeight, $newWeight, $filters, $weightField);
358 * Looks up max weight for a set of sortable entities
360 * Keeps it in memory in case this operation is writing more than one record
364 * @param $weightField
367 private function getMaxWeight($daoName, $filters, $weightField) {
368 $key = $daoName . json_encode($filters);
369 if (!isset($this->_maxWeights
[$key])) {
370 $this->_maxWeights
[$key] = \CRM_Utils_Weight
::getMax($daoName, $filters, $weightField) +
1;
373 ++
$this->_maxWeights
[$key];
375 return $this->_maxWeights
[$key];