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