APIv4 - Deprecate and stop using PreSaveSubscriber
[civicrm-core.git] / Civi / Api4 / Action / CustomField / CustomFieldSaveTrait.php
CommitLineData
19b53e5b
C
1<?php
2
380f3545
TO
3/*
4 +--------------------------------------------------------------------+
41498ac5 5 | Copyright CiviCRM LLC. All rights reserved. |
380f3545 6 | |
41498ac5
TO
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 |
380f3545
TO
10 +--------------------------------------------------------------------+
11 */
12
ed3f5877 13namespace Civi\Api4\Action\CustomField;
19b53e5b 14
ed3f5877
CW
15/**
16 * Code shared by CustomField create/update/save actions
17 */
18trait CustomFieldSaveTrait {
19b53e5b 19
18dd1d5f 20 /**
ed3f5877 21 * @inheritDoc
18dd1d5f 22 */
ed3f5877
CW
23 protected function write(array $items) {
24 foreach ($items as &$field) {
25 if (empty($field['id'])) {
26 self::formatOptionValues($field);
27 }
28 }
29 return parent::write($items);
30 }
19b53e5b 31
ed3f5877
CW
32 /**
33 * If 'option_values' have been supplied, reformat it according to the expectations of the BAO
34 *
35 * @param array $field
36 */
37 private static function formatOptionValues(array &$field): void {
38 $field['option_type'] = !empty($field['option_values']);
19b53e5b 39 if (!empty($field['option_values'])) {
ed3f5877
CW
40 $weight = 0;
41 $field['option_label'] = $field['option_value'] = $field['option_status'] = $field['option_weight'] =
bb6bfd68 42 $field['option_name'] = $field['option_color'] = $field['option_description'] = $field['option_icon'] = [];
19b53e5b
C
43 foreach ($field['option_values'] as $key => $value) {
44 // Translate simple key/value pairs into full-blown option values
45 if (!is_array($value)) {
46 $value = [
47 'label' => $value,
bb6bfd68 48 'id' => $key,
19b53e5b 49 ];
19b53e5b 50 }
bb6bfd68
CW
51 $field['option_label'][] = $value['label'] ?? $value['name'];
52 $field['option_name'][] = $value['name'] ?? NULL;
53 $field['option_value'][] = $value['id'];
54 $field['option_status'][] = $value['is_active'] ?? 1;
ed3f5877 55 $field['option_weight'][] = $value['weight'] ?? ++$weight;
bb6bfd68
CW
56 $field['option_color'][] = $value['color'] ?? NULL;
57 $field['option_description'][] = $value['description'] ?? NULL;
58 $field['option_icon'][] = $value['icon'] ?? NULL;
19b53e5b
C
59 }
60 }
19b53e5b
C
61 }
62
63}