Commit | Line | Data |
---|---|---|
30f5345c TO |
1 | <?php |
2 | ||
3 | namespace Civi\Test; | |
4 | ||
62950ef9 CW |
5 | use Civi\API\Exception\NotImplementedException; |
6 | ||
7f32c217 | 7 | require_once 'api/v3/utils.php'; |
30f5345c TO |
8 | /** |
9 | * Class Api3TestTrait | |
10 | * @package Civi\Test | |
11 | * | |
12 | * This trait defines a number of helper functions for testing APIv3. Commonly | |
13 | * used helpers include `callAPISuccess()`, `callAPIFailure()`, | |
14 | * `assertAPISuccess()`, and `assertAPIFailure()`. | |
15 | * | |
16 | * This trait is intended for use with PHPUnit-based test cases. | |
17 | */ | |
18 | trait Api3TestTrait { | |
19 | ||
62950ef9 CW |
20 | /** |
21 | * Get the api versions to test. | |
22 | * | |
23 | * @return array | |
24 | */ | |
25 | public function versionThreeAndFour() { | |
89f5231f CW |
26 | return [ |
27 | 'APIv3' => [3], | |
28 | 'APIv4' => [4], | |
29 | ]; | |
62950ef9 CW |
30 | } |
31 | ||
30f5345c TO |
32 | /** |
33 | * Api version - easier to override than just a define | |
34f3bbd9 | 34 | * @var int |
30f5345c TO |
35 | */ |
36 | protected $_apiversion = 3; | |
37 | ||
38 | /** | |
39 | * Check that api returned 'is_error' => 1 | |
40 | * else provide full message | |
41 | * @param array $result | |
42 | * @param $expected | |
43 | * @param array $valuesToExclude | |
44 | * @param string $prefix | |
45 | * Extra test to add to message. | |
46 | */ | |
c64f69d9 CW |
47 | public function assertAPIArrayComparison($result, $expected, $valuesToExclude = [], $prefix = '') { |
48 | $valuesToExclude = array_merge($valuesToExclude, ['debug', 'xdebug', 'sequential']); | |
30f5345c TO |
49 | foreach ($valuesToExclude as $value) { |
50 | if (isset($result[$value])) { | |
51 | unset($result[$value]); | |
52 | } | |
53 | if (isset($expected[$value])) { | |
54 | unset($expected[$value]); | |
55 | } | |
56 | } | |
57 | $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE)); | |
58 | } | |
59 | ||
60 | /** | |
61 | * Check that a deleted item has been deleted. | |
62 | * | |
63 | * @param $entity | |
64 | * @param $id | |
65 | */ | |
66 | public function assertAPIDeleted($entity, $id) { | |
c64f69d9 | 67 | $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0); |
30f5345c TO |
68 | } |
69 | ||
70 | /** | |
71 | * Check that api returned 'is_error' => 1. | |
72 | * | |
73 | * @param array $apiResult | |
74 | * Api result. | |
75 | * @param string $prefix | |
76 | * Extra test to add to message. | |
77 | * @param null $expectedError | |
78 | */ | |
79 | public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) { | |
80 | if (!empty($prefix)) { | |
81 | $prefix .= ': '; | |
82 | } | |
83 | if ($expectedError && !empty($apiResult['is_error'])) { | |
62950ef9 | 84 | $this->assertContains($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix); |
30f5345c TO |
85 | } |
86 | $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE))); | |
87 | $this->assertNotEmpty($apiResult['error_message']); | |
88 | } | |
89 | ||
90 | /** | |
91 | * Check that api returned 'is_error' => 0. | |
92 | * | |
93 | * @param array $apiResult | |
94 | * Api result. | |
95 | * @param string $prefix | |
96 | * Extra test to add to message. | |
97 | */ | |
98 | public function assertAPISuccess($apiResult, $prefix = '') { | |
99 | if (!empty($prefix)) { | |
100 | $prefix .= ': '; | |
101 | } | |
102 | $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message']; | |
103 | ||
104 | if (!empty($apiResult['debug_information'])) { | |
105 | $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE); | |
106 | } | |
107 | if (!empty($apiResult['trace'])) { | |
108 | $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE); | |
109 | } | |
a2ff62ce | 110 | $this->assertEmpty($apiResult['is_error'] ?? NULL, $prefix . $errorMessage); |
30f5345c TO |
111 | } |
112 | ||
113 | /** | |
114 | * This function exists to wrap api functions. | |
115 | * so we can ensure they fail where expected & throw exceptions without litterering the test with checks | |
116 | * @param string $entity | |
117 | * @param string $action | |
118 | * @param array $params | |
119 | * @param string $expectedErrorMessage | |
120 | * Error. | |
121 | * @param null $extraOutput | |
122 | * @return array|int | |
123 | */ | |
124 | public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) { | |
125 | if (is_array($params)) { | |
c64f69d9 | 126 | $params += [ |
30f5345c | 127 | 'version' => $this->_apiversion, |
c64f69d9 | 128 | ]; |
30f5345c TO |
129 | } |
130 | $result = $this->civicrm_api($entity, $action, $params); | |
131 | $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage); | |
132 | return $result; | |
133 | } | |
134 | ||
135 | /** | |
136 | * wrap api functions. | |
137 | * so we can ensure they succeed & throw exceptions without litterering the test with checks | |
138 | * | |
139 | * @param string $entity | |
140 | * @param string $action | |
141 | * @param array $params | |
142 | * @param mixed $checkAgainst | |
143 | * Optional value to check result against, implemented for getvalue,. | |
144 | * getcount, getsingle. Note that for getvalue the type is checked rather than the value | |
145 | * for getsingle the array is compared against an array passed in - the id is not compared (for | |
146 | * better or worse ) | |
147 | * | |
148 | * @return array|int | |
e2887a3c | 149 | * |
150 | * @throws \CRM_Core_Exception | |
30f5345c | 151 | */ |
62950ef9 | 152 | public function callAPISuccess($entity, $action, $params = [], $checkAgainst = NULL) { |
c64f69d9 | 153 | $params = array_merge([ |
30f5345c TO |
154 | 'version' => $this->_apiversion, |
155 | 'debug' => 1, | |
c64f69d9 | 156 | ], |
30f5345c TO |
157 | $params |
158 | ); | |
159 | switch (strtolower($action)) { | |
160 | case 'getvalue': | |
161 | return $this->callAPISuccessGetValue($entity, $params, $checkAgainst); | |
162 | ||
163 | case 'getsingle': | |
164 | return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst); | |
165 | ||
166 | case 'getcount': | |
167 | return $this->callAPISuccessGetCount($entity, $params, $checkAgainst); | |
168 | } | |
169 | $result = $this->civicrm_api($entity, $action, $params); | |
170 | $this->assertAPISuccess($result, "Failure in api call for $entity $action"); | |
171 | return $result; | |
172 | } | |
173 | ||
174 | /** | |
175 | * This function exists to wrap api getValue function & check the result | |
176 | * so we can ensure they succeed & throw exceptions without litterering the test with checks | |
177 | * There is a type check in this | |
023f9e8a | 178 | * |
30f5345c TO |
179 | * @param string $entity |
180 | * @param array $params | |
023f9e8a | 181 | * @param int $count |
182 | * | |
183 | * @throws \CRM_Core_Exception | |
184 | * | |
30f5345c TO |
185 | * @return array|int |
186 | */ | |
187 | public function callAPISuccessGetCount($entity, $params, $count = NULL) { | |
c64f69d9 | 188 | $params += [ |
30f5345c TO |
189 | 'version' => $this->_apiversion, |
190 | 'debug' => 1, | |
c64f69d9 | 191 | ]; |
30f5345c TO |
192 | $result = $this->civicrm_api($entity, 'getcount', $params); |
193 | if (!is_int($result) || !empty($result['is_error']) || isset($result['values'])) { | |
023f9e8a | 194 | throw new \CRM_Core_Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result)); |
30f5345c TO |
195 | } |
196 | if (is_int($count)) { | |
197 | $this->assertEquals($count, $result, "incorrect count returned from $entity getcount"); | |
198 | } | |
199 | return $result; | |
200 | } | |
201 | ||
202 | /** | |
203 | * This function exists to wrap api getsingle function & check the result | |
204 | * so we can ensure they succeed & throw exceptions without litterering the test with checks | |
205 | * | |
206 | * @param string $entity | |
207 | * @param array $params | |
208 | * @param array $checkAgainst | |
209 | * Array to compare result against. | |
210 | * - boolean | |
211 | * - integer | |
212 | * - double | |
213 | * - string | |
214 | * - array | |
215 | * - object | |
216 | * | |
023f9e8a | 217 | * @throws \CRM_Core_Exception |
218 | * | |
30f5345c TO |
219 | * @return array|int |
220 | */ | |
221 | public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) { | |
c64f69d9 | 222 | $params += [ |
30f5345c | 223 | 'version' => $this->_apiversion, |
c64f69d9 | 224 | ]; |
30f5345c TO |
225 | $result = $this->civicrm_api($entity, 'getsingle', $params); |
226 | if (!is_array($result) || !empty($result['is_error']) || isset($result['values'])) { | |
023f9e8a | 227 | $unfilteredResult = $this->civicrm_api($entity, 'get', ['version' => $this->_apiversion]); |
228 | throw new \CRM_Core_Exception( | |
cb4e7d31 | 229 | 'Invalid getsingle result' . print_r($result, TRUE) |
230 | . "\n entity: $entity . \n params \n " . print_r($params, TRUE) | |
34f3bbd9 | 231 | . "\n entities retrieved with blank params \n" . print_r($unfilteredResult, TRUE) |
cb4e7d31 | 232 | ); |
30f5345c TO |
233 | } |
234 | if ($checkAgainst) { | |
235 | // @todo - have gone with the fn that unsets id? should we check id? | |
236 | $this->checkArrayEquals($result, $checkAgainst); | |
237 | } | |
238 | return $result; | |
239 | } | |
240 | ||
241 | /** | |
242 | * This function exists to wrap api getValue function & check the result | |
243 | * so we can ensure they succeed & throw exceptions without litterering the test with checks | |
244 | * There is a type check in this | |
245 | * | |
246 | * @param string $entity | |
247 | * @param array $params | |
248 | * @param string $type | |
249 | * Per http://php.net/manual/en/function.gettype.php possible types. | |
250 | * - boolean | |
251 | * - integer | |
252 | * - double | |
253 | * - string | |
254 | * - array | |
255 | * - object | |
256 | * | |
257 | * @return array|int | |
5214f03b | 258 | * @throws \CRM_Core_Exception |
30f5345c TO |
259 | */ |
260 | public function callAPISuccessGetValue($entity, $params, $type = NULL) { | |
c64f69d9 | 261 | $params += [ |
30f5345c TO |
262 | 'version' => $this->_apiversion, |
263 | 'debug' => 1, | |
c64f69d9 | 264 | ]; |
30f5345c | 265 | $result = $this->civicrm_api($entity, 'getvalue', $params); |
1bf00882 | 266 | if (is_array($result) && (!empty($result['is_error']) || isset($result['values']))) { |
5214f03b | 267 | throw new \CRM_Core_Exception('Invalid getvalue result' . print_r($result, TRUE)); |
1bf00882 | 268 | } |
30f5345c | 269 | if ($type) { |
5214f03b | 270 | if ($type === 'integer') { |
30f5345c TO |
271 | // api seems to return integers as strings |
272 | $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1)); | |
273 | } | |
274 | else { | |
275 | $this->assertType($type, $result, "returned result should have been of type $type but was "); | |
276 | } | |
277 | } | |
278 | return $result; | |
279 | } | |
280 | ||
281 | /** | |
282 | * A stub for the API interface. This can be overriden by subclasses to change how the API is called. | |
283 | * | |
284 | * @param $entity | |
285 | * @param $action | |
286 | * @param array $params | |
287 | * @return array|int | |
288 | */ | |
62950ef9 | 289 | public function civicrm_api($entity, $action, $params = []) { |
a2ff62ce | 290 | if (($params['version'] ?? 0) == 4) { |
62950ef9 CW |
291 | return $this->runApi4Legacy($entity, $action, $params); |
292 | } | |
30f5345c TO |
293 | return civicrm_api($entity, $action, $params); |
294 | } | |
295 | ||
62950ef9 CW |
296 | /** |
297 | * Emulate v3 syntax so we can run api3 tests on v4 | |
298 | * | |
299 | * @param $v3Entity | |
300 | * @param $v3Action | |
301 | * @param array $v3Params | |
302 | * @return array|int | |
303 | * @throws \API_Exception | |
304 | * @throws \CiviCRM_API3_Exception | |
305 | * @throws \Exception | |
306 | */ | |
307 | public function runApi4Legacy($v3Entity, $v3Action, $v3Params = []) { | |
74c303ca | 308 | $v4Entity = \CRM_Core_DAO_AllCoreTables::convertEntityNameToCamel($v3Entity); |
62950ef9 CW |
309 | $v4Action = $v3Action = strtolower($v3Action); |
310 | $v4Params = ['checkPermissions' => isset($v3Params['check_permissions']) ? (bool) $v3Params['check_permissions'] : FALSE]; | |
311 | $sequential = !empty($v3Params['sequential']); | |
312 | $options = \_civicrm_api3_get_options_from_params($v3Params, in_array($v4Entity, ['Contact', 'Participant', 'Event', 'Group', 'Contribution', 'Membership'])); | |
313 | $indexBy = in_array($v3Action, ['get', 'create', 'replace']) && !$sequential ? 'id' : NULL; | |
314 | $onlyId = !empty($v3Params['format.only_id']); | |
315 | $onlySuccess = !empty($v3Params['format.is_success']); | |
3e20c1ac | 316 | if (!empty($v3Params['filters']['is_current']) || !empty($v3Params['isCurrent'])) { |
62950ef9 CW |
317 | $v4Params['current'] = TRUE; |
318 | } | |
a2ff62ce | 319 | $language = $v3Params['options']['language'] ?? $v3Params['option.language'] ?? NULL; |
3e20c1ac CW |
320 | if ($language) { |
321 | $v4Params['language'] = $language; | |
322 | } | |
62950ef9 | 323 | $toRemove = ['option.', 'return', 'api.', 'format.']; |
3493febb | 324 | $chains = $joins = $custom = []; |
62950ef9 CW |
325 | foreach ($v3Params as $key => $val) { |
326 | foreach ($toRemove as $remove) { | |
327 | if (strpos($key, $remove) === 0) { | |
328 | if ($remove == 'api.') { | |
329 | $chains[$key] = $val; | |
330 | } | |
331 | unset($v3Params[$key]); | |
332 | } | |
333 | } | |
334 | } | |
335 | ||
336 | $v3Fields = civicrm_api3($v3Entity, 'getfields', ['action' => $v3Action])['values']; | |
337 | ||
338 | // Fix 'null' | |
339 | foreach ($v3Params as $key => $val) { | |
340 | if ($val === 'null') { | |
341 | $v3Params[$key] = NULL; | |
342 | } | |
343 | } | |
344 | ||
345 | if ($v4Entity == 'Setting') { | |
346 | $indexBy = NULL; | |
a2ff62ce | 347 | $v4Params['domainId'] = $v3Params['domain_id'] ?? NULL; |
62950ef9 CW |
348 | if ($v3Action == 'getfields') { |
349 | if (!empty($v3Params['name'])) { | |
350 | $v3Params['filters']['name'] = $v3Params['name']; | |
351 | } | |
a2ff62ce | 352 | foreach ($v3Params['filters'] ?? [] as $filter => $val) { |
62950ef9 CW |
353 | $v4Params['where'][] = [$filter, '=', $val]; |
354 | } | |
355 | } | |
356 | if ($v3Action == 'create') { | |
357 | $v4Action = 'set'; | |
358 | } | |
359 | if ($v3Action == 'revert') { | |
360 | $v4Params['select'] = (array) $v3Params['name']; | |
361 | } | |
362 | if ($v3Action == 'getvalue') { | |
363 | $options['return'] = [$v3Params['name'] => 1]; | |
364 | $v3Params = []; | |
365 | } | |
366 | \CRM_Utils_Array::remove($v3Params, 'domain_id', 'name'); | |
367 | } | |
368 | ||
369 | \CRM_Utils_Array::remove($v3Params, 'options', 'debug', 'version', 'sort', 'offset', 'rowCount', 'check_permissions', 'sequential', 'filters', 'isCurrent'); | |
370 | ||
371 | // Work around ugly hack in v3 Domain api | |
372 | if ($v4Entity == 'Domain') { | |
373 | $v3Fields['version'] = ['name' => 'version', 'api.aliases' => ['domain_version']]; | |
374 | unset($v3Fields['domain_version']); | |
375 | } | |
376 | ||
377 | foreach ($v3Fields as $name => $field) { | |
378 | // Resolve v3 aliases | |
a2ff62ce | 379 | foreach ($field['api.aliases'] ?? [] as $alias) { |
62950ef9 CW |
380 | if (isset($v3Params[$alias])) { |
381 | $v3Params[$field['name']] = $v3Params[$alias]; | |
382 | unset($v3Params[$alias]); | |
383 | } | |
384 | } | |
385 | // Convert custom field names | |
386 | if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) { | |
387 | // Strictly speaking, using titles instead of names is incorrect, but it works for | |
388 | // unit tests where names and titles are identical and saves an extra db lookup. | |
389 | $custom[$field['groupTitle']][$field['title']] = $name; | |
390 | $v4FieldName = $field['groupTitle'] . '.' . $field['title']; | |
391 | if (isset($v3Params[$name])) { | |
392 | $v3Params[$v4FieldName] = $v3Params[$name]; | |
393 | unset($v3Params[$name]); | |
394 | } | |
395 | if (isset($options['return'][$name])) { | |
396 | $options['return'][$v4FieldName] = 1; | |
397 | unset($options['return'][$name]); | |
398 | } | |
399 | } | |
1441a378 | 400 | |
401 | if ($name === 'option_group_id' && isset($v3Params[$name]) && !is_numeric($v3Params[$name])) { | |
402 | // This is a per field hack (bad) but we can't solve everything at once | |
403 | // & a cleverer way turned out to be too much for this round. | |
404 | // Being in the test class it's tested.... | |
405 | $v3Params['option_group.name'] = $v3Params['option_group_id']; | |
406 | unset($v3Params['option_group_id']); | |
407 | } | |
62950ef9 CW |
408 | } |
409 | ||
410 | switch ($v3Action) { | |
411 | case 'getcount': | |
412 | $v4Params['select'] = ['row_count']; | |
413 | // No break - keep processing as get | |
414 | case 'getsingle': | |
415 | case 'getvalue': | |
416 | $v4Action = 'get'; | |
417 | // No break - keep processing as get | |
418 | case 'get': | |
419 | if ($options['return'] && $v3Action !== 'getcount') { | |
420 | $v4Params['select'] = array_keys($options['return']); | |
8e593ba8 CW |
421 | // Ensure id field is returned as v3 always expects it |
422 | if ($v4Entity != 'Setting' && !in_array('id', $v4Params['select'])) { | |
423 | $v4Params['select'][] = 'id'; | |
424 | } | |
3493febb CW |
425 | // Convert join syntax |
426 | foreach ($v4Params['select'] as &$select) { | |
427 | if (strstr($select, '_id.')) { | |
428 | $joins[$select] = explode('.', str_replace('_id.', '.', $select)); | |
429 | $select = str_replace('_id.', '.', $select); | |
430 | } | |
431 | } | |
62950ef9 CW |
432 | } |
433 | if ($options['limit'] && $v4Entity != 'Setting') { | |
434 | $v4Params['limit'] = $options['limit']; | |
435 | } | |
436 | if ($options['offset']) { | |
437 | $v4Params['offset'] = $options['offset']; | |
438 | } | |
439 | if ($options['sort']) { | |
440 | foreach (explode(',', $options['sort']) as $sort) { | |
441 | list($sortField, $sortDir) = array_pad(explode(' ', trim($sort)), 2, 'ASC'); | |
442 | $v4Params['orderBy'][$sortField] = $sortDir; | |
443 | } | |
444 | } | |
445 | break; | |
446 | ||
447 | case 'replace': | |
448 | if (empty($v3Params['values'])) { | |
449 | $v4Action = 'delete'; | |
450 | } | |
451 | else { | |
452 | $v4Params['records'] = $v3Params['values']; | |
453 | } | |
454 | unset($v3Params['values']); | |
455 | break; | |
456 | ||
457 | case 'create': | |
458 | case 'update': | |
459 | if (!empty($v3Params['id'])) { | |
460 | $v4Action = 'update'; | |
461 | $v4Params['where'][] = ['id', '=', $v3Params['id']]; | |
462 | } | |
463 | ||
464 | $v4Params['values'] = $v3Params; | |
465 | unset($v4Params['values']['id']); | |
466 | break; | |
467 | ||
468 | case 'delete': | |
8a0c3604 | 469 | if (isset($v3Params['id'])) { |
62950ef9 CW |
470 | $v4Params['where'][] = ['id', '=', $v3Params['id']]; |
471 | } | |
472 | break; | |
473 | ||
474 | case 'getoptions': | |
475 | $indexBy = 0; | |
476 | $v4Action = 'getFields'; | |
477 | $v4Params += [ | |
478 | 'where' => [['name', '=', $v3Params['field']]], | |
479 | 'loadOptions' => TRUE, | |
480 | ]; | |
481 | break; | |
482 | ||
483 | case 'getfields': | |
484 | $v4Action = 'getFields'; | |
485 | if (!empty($v3Params['action']) || !empty($v3Params['api_action'])) { | |
486 | $v4Params['action'] = !empty($v3Params['action']) ? $v3Params['action'] : $v3Params['api_action']; | |
487 | } | |
488 | $indexBy = !$sequential ? 'name' : NULL; | |
489 | break; | |
490 | } | |
491 | ||
492 | // Ensure this api4 entity/action exists | |
493 | try { | |
494 | $actionInfo = \civicrm_api4($v4Entity, 'getActions', ['checkPermissions' => FALSE, 'where' => [['name', '=', $v4Action]]]); | |
495 | } | |
496 | catch (NotImplementedException $e) { | |
497 | // For now we'll mark the test incomplete if a v4 entity doesn't exit yet | |
498 | $this->markTestIncomplete($e->getMessage()); | |
499 | } | |
500 | if (!isset($actionInfo[0])) { | |
501 | throw new \Exception("Api4 $v4Entity $v4Action does not exist."); | |
502 | } | |
503 | ||
504 | // Migrate special params like fix_address | |
505 | foreach ($actionInfo[0]['params'] as $v4ParamName => $paramInfo) { | |
506 | // camelCase in api4, lower_case in api3 | |
507 | $v3ParamName = strtolower(preg_replace('/(?=[A-Z])/', '_$0', $v4ParamName)); | |
508 | if (isset($v3Params[$v3ParamName])) { | |
509 | $v4Params[$v4ParamName] = $v3Params[$v3ParamName]; | |
510 | unset($v3Params[$v3ParamName]); | |
511 | if ($paramInfo['type'][0] == 'bool') { | |
512 | $v4Params[$v4ParamName] = (bool) $v4Params[$v4ParamName]; | |
513 | } | |
514 | } | |
515 | } | |
516 | ||
517 | // Build where clause for 'getcount', 'getsingle', 'getvalue', 'get' & 'replace' | |
518 | if ($v4Action == 'get' || $v3Action == 'replace') { | |
519 | foreach ($v3Params as $key => $val) { | |
520 | $op = '='; | |
521 | if (is_array($val) && count($val) == 1 && array_intersect_key($val, array_flip(\CRM_Core_DAO::acceptedSQLOperators()))) { | |
522 | foreach ($val as $op => $newVal) { | |
523 | $val = $newVal; | |
524 | } | |
525 | } | |
526 | $v4Params['where'][] = [$key, $op, $val]; | |
527 | } | |
528 | } | |
529 | ||
530 | try { | |
531 | $result = \civicrm_api4($v4Entity, $v4Action, $v4Params, $indexBy); | |
532 | } | |
533 | catch (\Exception $e) { | |
534 | return $onlySuccess ? 0 : [ | |
535 | 'is_error' => 1, | |
536 | 'error_message' => $e->getMessage(), | |
537 | 'version' => 4, | |
538 | ]; | |
539 | } | |
540 | ||
8a0c3604 | 541 | if (($v3Action == 'getsingle' || $v3Action == 'getvalue' || $v3Action == 'delete') && count($result) != 1) { |
62950ef9 CW |
542 | return $onlySuccess ? 0 : [ |
543 | 'is_error' => 1, | |
544 | 'error_message' => "Expected one $v4Entity but found " . count($result), | |
545 | 'count' => count($result), | |
546 | ]; | |
547 | } | |
548 | ||
549 | if ($onlySuccess) { | |
550 | return 1; | |
551 | } | |
552 | ||
553 | if ($v3Action == 'getcount') { | |
554 | return $result->count(); | |
555 | } | |
556 | ||
557 | if ($onlyId) { | |
558 | return $result->first()['id']; | |
559 | } | |
560 | ||
561 | if ($v3Action == 'getvalue' && $v4Entity == 'Setting') { | |
a2ff62ce | 562 | return $result->first()['value'] ?? NULL; |
62950ef9 CW |
563 | } |
564 | ||
565 | if ($v3Action == 'getvalue') { | |
a2ff62ce CW |
566 | $returnKey = array_keys($options['return'])[0]; |
567 | return $result->first()[$returnKey] ?? NULL; | |
62950ef9 CW |
568 | } |
569 | ||
570 | // Mimic api3 behavior when using 'replace' action to delete all | |
571 | if ($v3Action == 'replace' && $v4Action == 'delete') { | |
572 | $result->exchangeArray([]); | |
573 | } | |
574 | ||
575 | if ($v3Action == 'getoptions') { | |
576 | return [ | |
577 | 'is_error' => 0, | |
578 | 'count' => $result['options'] ? count($result['options']) : 0, | |
579 | 'values' => $result['options'] ?: [], | |
580 | 'version' => 4, | |
581 | ]; | |
582 | } | |
583 | ||
584 | // Emulate the weird return format of api3 settings | |
585 | if (($v3Action == 'get' || $v3Action == 'create') && $v4Entity == 'Setting') { | |
586 | $settings = []; | |
587 | foreach ($result as $item) { | |
588 | $settings[$item['domain_id']][$item['name']] = $item['value']; | |
589 | } | |
590 | $result->exchangeArray($sequential ? array_values($settings) : $settings); | |
591 | } | |
592 | ||
593 | foreach ($result as $index => $row) { | |
594 | // Run chains | |
595 | foreach ($chains as $key => $params) { | |
596 | $result[$index][$key] = $this->runApi4LegacyChain($key, $params, $v4Entity, $row, $sequential); | |
597 | } | |
3493febb CW |
598 | // Convert join format |
599 | foreach ($joins as $api3Key => $api4Path) { | |
600 | $result[$index][$api3Key] = \CRM_Utils_Array::pathGet($result[$index], $api4Path); | |
601 | } | |
62950ef9 CW |
602 | // Resolve custom field names |
603 | foreach ($custom as $group => $fields) { | |
f74361a9 CW |
604 | foreach ($fields as $field => $v3FieldName) { |
605 | if (isset($row["$group.$field"])) { | |
606 | $result[$index][$v3FieldName] = $row["$group.$field"]; | |
607 | unset($result[$index]["$group.$field"]); | |
62950ef9 | 608 | } |
62950ef9 CW |
609 | } |
610 | } | |
611 | } | |
612 | ||
613 | if ($v3Action == 'getsingle') { | |
614 | return $result->first(); | |
615 | } | |
616 | ||
617 | return [ | |
618 | 'is_error' => 0, | |
619 | 'version' => 4, | |
620 | 'count' => count($result), | |
621 | 'values' => (array) $result, | |
a2ff62ce | 622 | 'id' => is_object($result) && count($result) == 1 ? ($result->first()['id'] ?? NULL) : NULL, |
62950ef9 CW |
623 | ]; |
624 | } | |
625 | ||
626 | /** | |
627 | * @param string $key | |
628 | * @param mixed $params | |
629 | * @param string $mainEntity | |
630 | * @param array $result | |
631 | * @param bool $sequential | |
632 | * @return array | |
633 | * @throws \API_Exception | |
634 | */ | |
635 | protected function runApi4LegacyChain($key, $params, $mainEntity, $result, $sequential) { | |
636 | // Handle an array of multiple calls using recursion | |
637 | if (is_array($params) && isset($params[0]) && is_array($params[0])) { | |
638 | $results = []; | |
639 | foreach ($params as $chain) { | |
640 | $results[] = $this->runApi4LegacyChain($key, $chain, $mainEntity, $result, $sequential); | |
641 | } | |
642 | return $results; | |
643 | } | |
644 | ||
645 | // Handle single api call | |
646 | list(, $chainEntity, $chainAction) = explode('.', $key); | |
74c303ca | 647 | $lcChainEntity = \CRM_Core_DAO_AllCoreTables::convertEntityNameToLower($chainEntity); |
648 | $chainEntity = \CRM_Core_DAO_AllCoreTables::convertEntityNameToCamel($chainEntity); | |
649 | $lcMainEntity = \CRM_Core_DAO_AllCoreTables::convertEntityNameToLower($mainEntity); | |
62950ef9 CW |
650 | $params = is_array($params) ? $params : []; |
651 | ||
652 | // Api3 expects this to be inherited | |
653 | $params += ['sequential' => $sequential]; | |
654 | ||
655 | // Replace $value.field_name | |
656 | foreach ($params as $name => $param) { | |
657 | if (is_string($param) && strpos($param, '$value.') === 0) { | |
658 | $param = substr($param, 7); | |
a2ff62ce | 659 | $params[$name] = $result[$param] ?? NULL; |
62950ef9 CW |
660 | } |
661 | } | |
662 | ||
663 | try { | |
664 | $getFields = civicrm_api4($chainEntity, 'getFields', ['select' => ['name']], 'name'); | |
665 | } | |
666 | catch (NotImplementedException $e) { | |
667 | $this->markTestIncomplete($e->getMessage()); | |
668 | } | |
669 | ||
670 | // Emulate the string-fu guesswork that api3 does | |
671 | if ($chainEntity == $mainEntity && empty($params['id']) && !empty($result['id'])) { | |
672 | $params['id'] = $result['id']; | |
673 | } | |
674 | elseif (empty($params['id']) && !empty($result[$lcChainEntity . '_id'])) { | |
675 | $params['id'] = $result[$lcChainEntity . '_id']; | |
676 | } | |
677 | elseif (!empty($result['id']) && isset($getFields[$lcMainEntity . '_id']) && empty($params[$lcMainEntity . '_id'])) { | |
678 | $params[$lcMainEntity . '_id'] = $result['id']; | |
679 | } | |
680 | return $this->runApi4Legacy($chainEntity, $chainAction, $params); | |
681 | } | |
682 | ||
30f5345c | 683 | } |