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