Merge pull request #18252 from JKingsnorth/core-1971-fix
[civicrm-core.git] / Civi / Api4 / Generic / BasicGetFieldsAction.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
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 +--------------------------------------------------------------------+
11 */
12
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18
19
20 namespace Civi\Api4\Generic;
21
22 use Civi\API\Exception\NotImplementedException;
23
24 /**
25 * Lists information about fields for the $ENTITY entity.
26 *
27 * This field information is also known as "metadata."
28 *
29 * Note that different actions may support different lists of fields.
30 * By default this will fetch the field list relevant to `get`,
31 * but a different list may be returned if you specify another action.
32 *
33 * @method $this setLoadOptions(bool|array $value)
34 * @method bool|array getLoadOptions()
35 * @method $this setAction(string $value)
36 * @method $this setValues(array $values)
37 * @method array getValues()
38 */
39 class BasicGetFieldsAction extends BasicGetAction {
40
41 /**
42 * Fetch option lists for fields?
43 *
44 * This parameter can be either a boolean or an array of attributes to return from the option list:
45 *
46 * - If `FALSE`, each field's `options` property will be a boolean indicating whether the field has an option list
47 * - If `TRUE`, `options` will be returned as a flat array of the option list's `[id => label]`
48 * - If an array, `options` will be a non-associative array of requested properties:
49 * id, name, label, abbr, description, color, icon
50 * e.g. `loadOptions: ['id', 'name', 'label']` will return an array like `[[id: 1, name: 'Meeting', label: 'Meeting'], ...]`
51 * (note that names and labels are generally ONLY the same when the site's language is set to English).
52 *
53 * @var bool|array
54 */
55 protected $loadOptions = FALSE;
56
57 /**
58 * Fields will be returned appropriate to the specified action (get, create, delete, etc.)
59 *
60 * @var string
61 */
62 protected $action = 'get';
63
64 /**
65 * Fields will be returned appropriate to the specified values (e.g. ['contact_type' => 'Individual'])
66 *
67 * @var array
68 */
69 protected $values = [];
70
71 /**
72 * To implement getFields for your own entity:
73 *
74 * 1. From your entity class add a static getFields method.
75 * 2. That method should construct and return this class.
76 * 3. The 3rd argument passed to this constructor should be a function that returns an
77 * array of fields for your entity's CRUD actions.
78 * 4. For non-crud actions that need a different set of fields, you can override the
79 * list from step 3 on a per-action basis by defining a fields() method in that action.
80 * See for example BasicGetFieldsAction::fields() or GetActions::fields().
81 *
82 * @param Result $result
83 * @throws \Civi\API\Exception\NotImplementedException
84 */
85 public function _run(Result $result) {
86 try {
87 $actionClass = \Civi\API\Request::create($this->getEntityName(), $this->getAction(), ['version' => 4]);
88 }
89 catch (NotImplementedException $e) {
90 }
91 if (isset($actionClass) && method_exists($actionClass, 'fields')) {
92 $values = $actionClass->fields();
93 }
94 else {
95 $values = $this->getRecords();
96 }
97 $this->formatResults($values);
98 $this->queryArray($values, $result);
99 }
100
101 /**
102 * Ensure every result contains, at minimum, the array keys as defined in $this->fields.
103 *
104 * Attempt to set some sensible defaults for some fields.
105 *
106 * Format option lists.
107 *
108 * In most cases it's not necessary to override this function, even if your entity is really weird.
109 * Instead just override $this->fields and this function will respect that.
110 *
111 * @param array $values
112 */
113 protected function formatResults(&$values) {
114 $fields = array_column($this->fields(), 'name');
115 // Enforce field permissions
116 if ($this->checkPermissions) {
117 foreach ($values as $key => $field) {
118 if (!empty($field['permission']) && !\CRM_Core_Permission::check($field['permission'])) {
119 unset($values[$key]);
120 }
121 }
122 }
123 foreach ($values as &$field) {
124 $defaults = array_intersect_key([
125 'title' => empty($field['name']) ? NULL : ucwords(str_replace('_', ' ', $field['name'])),
126 'entity' => $this->getEntityName(),
127 'required' => FALSE,
128 'options' => !empty($field['pseudoconstant']),
129 'data_type' => \CRM_Utils_Array::value('type', $field, 'String'),
130 ], array_flip($fields));
131 $field += $defaults;
132 $field['label'] = $field['label'] ?? $field['title'];
133 if (isset($defaults['options'])) {
134 $field['options'] = $this->formatOptionList($field['options']);
135 }
136 $field += array_fill_keys($fields, NULL);
137 }
138 }
139
140 /**
141 * Transforms option list into the format specified in $this->loadOptions
142 *
143 * @param $options
144 * @return array|bool
145 */
146 private function formatOptionList($options) {
147 if (!$this->loadOptions || !is_array($options)) {
148 return (bool) $options;
149 }
150 if (!$options) {
151 return $options;
152 }
153 $formatted = [];
154 $first = reset($options);
155 // Flat array requested
156 if ($this->loadOptions === TRUE) {
157 // Convert non-associative to flat array
158 if (is_array($first) && isset($first['id'])) {
159 foreach ($options as $option) {
160 $formatted[$option['id']] = $option['label'] ?? $option['name'] ?? $option['id'];
161 }
162 return $formatted;
163 }
164 return $options;
165 }
166 // Non-associative array of multiple properties requested
167 foreach ($options as $id => $option) {
168 // Transform a flat list
169 if (!is_array($option)) {
170 $option = [
171 'id' => $id,
172 'name' => $option,
173 'label' => $option,
174 ];
175 }
176 $formatted[] = array_intersect_key($option, array_flip($this->loadOptions));
177 }
178 return $formatted;
179 }
180
181 /**
182 * @return string
183 */
184 public function getAction() {
185 // For actions that build on top of other actions, return fields for the simpler action
186 $sub = [
187 'save' => 'create',
188 'replace' => 'create',
189 ];
190 return $sub[$this->action] ?? $this->action;
191 }
192
193 /**
194 * Add an item to the values array
195 * @param string $fieldName
196 * @param mixed $value
197 * @return $this
198 */
199 public function addValue(string $fieldName, $value) {
200 $this->values[$fieldName] = $value;
201 return $this;
202 }
203
204 /**
205 * @param bool $includeCustom
206 * @return $this
207 */
208 public function setIncludeCustom(bool $includeCustom) {
209 // Be forgiving if the param doesn't exist and don't throw an exception
210 if (property_exists($this, 'includeCustom')) {
211 $this->includeCustom = $includeCustom;
212 }
213 return $this;
214 }
215
216 public function fields() {
217 return [
218 [
219 'name' => 'name',
220 'data_type' => 'String',
221 'description' => ts('Unique field identifier'),
222 ],
223 [
224 'name' => 'title',
225 'data_type' => 'String',
226 'description' => ts('Technical name of field, shown in API and exports'),
227 ],
228 [
229 'name' => 'label',
230 'data_type' => 'String',
231 'description' => ts('User-facing label, shown on most forms and displays'),
232 ],
233 [
234 'name' => 'description',
235 'data_type' => 'String',
236 'description' => ts('Explanation of the purpose of the field'),
237 ],
238 [
239 'name' => 'default_value',
240 'data_type' => 'String',
241 ],
242 [
243 'name' => 'required',
244 'data_type' => 'Boolean',
245 ],
246 [
247 'name' => 'required_if',
248 'data_type' => 'String',
249 ],
250 [
251 'name' => 'options',
252 'data_type' => 'Array',
253 ],
254 [
255 'name' => 'data_type',
256 'data_type' => 'String',
257 ],
258 [
259 'name' => 'input_type',
260 'data_type' => 'String',
261 ],
262 [
263 'name' => 'input_attrs',
264 'data_type' => 'Array',
265 ],
266 [
267 'name' => 'fk_entity',
268 'data_type' => 'String',
269 ],
270 [
271 'name' => 'serialize',
272 'data_type' => 'Integer',
273 ],
274 [
275 'name' => 'entity',
276 'data_type' => 'String',
277 ],
278 ];
279 }
280
281 }