5 use Civi\API\Exception\NotImplementedException
;
11 * This trait defines a number of helper functions for testing APIv3. Commonly
12 * used helpers include `callAPISuccess()`, `callAPIFailure()`,
13 * `assertAPISuccess()`, and `assertAPIFailure()`.
15 * This trait is intended for use with PHPUnit-based test cases.
20 * Get the api versions to test.
24 public function versionThreeAndFour() {
27 if (file_exists("$civicrm_root/Civi/Api4") ||
file_exists("$civicrm_root/ext/api4")) {
34 * Api version - easier to override than just a define
37 protected $_apiversion = 3;
40 * Check that api returned 'is_error' => 1
41 * else provide full message
42 * @param array $result
44 * @param array $valuesToExclude
45 * @param string $prefix
46 * Extra test to add to message.
48 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = [], $prefix = '') {
49 $valuesToExclude = array_merge($valuesToExclude, ['debug', 'xdebug', 'sequential']);
50 foreach ($valuesToExclude as $value) {
51 if (isset($result[$value])) {
52 unset($result[$value]);
54 if (isset($expected[$value])) {
55 unset($expected[$value]);
58 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
62 * Check that a deleted item has been deleted.
67 public function assertAPIDeleted($entity, $id) {
68 $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0);
72 * Check that api returned 'is_error' => 1.
74 * @param array $apiResult
76 * @param string $prefix
77 * Extra test to add to message.
78 * @param null $expectedError
80 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
81 if (!empty($prefix)) {
84 if ($expectedError && !empty($apiResult['is_error'])) {
85 $this->assertContains($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
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']);
92 * Check that api returned 'is_error' => 0.
94 * @param array $apiResult
96 * @param string $prefix
97 * Extra test to add to message.
99 public function assertAPISuccess($apiResult, $prefix = '') {
100 if (!empty($prefix)) {
103 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
105 if (!empty($apiResult['debug_information'])) {
106 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
108 if (!empty($apiResult['trace'])) {
109 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
111 $this->assertEmpty(\CRM_Utils_Array
::value('is_error', $apiResult), $prefix . $errorMessage);
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
122 * @param null $extraOutput
125 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
126 if (is_array($params)) {
128 'version' => $this->_apiversion
,
131 $result = $this->civicrm_api($entity, $action, $params);
132 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
137 * wrap api functions.
138 * so we can ensure they succeed & throw exceptions without litterering the test with checks
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
151 * @throws \CRM_Core_Exception
153 public function callAPISuccess($entity, $action, $params = [], $checkAgainst = NULL) {
154 $params = array_merge([
155 'version' => $this->_apiversion
,
160 switch (strtolower($action)) {
162 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
165 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
168 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
170 $result = $this->civicrm_api($entity, $action, $params);
171 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
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
180 * @param string $entity
181 * @param array $params
184 * @throws \CRM_Core_Exception
188 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
190 'version' => $this->_apiversion
,
193 $result = $this->civicrm_api($entity, 'getcount', $params);
194 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
195 throw new \
CRM_Core_Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
197 if (is_int($count)) {
198 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
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
207 * @param string $entity
208 * @param array $params
209 * @param array $checkAgainst
210 * Array to compare result against.
218 * @throws \CRM_Core_Exception
222 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
224 'version' => $this->_apiversion
,
226 $result = $this->civicrm_api($entity, 'getsingle', $params);
227 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
228 $unfilteredResult = $this->civicrm_api($entity, 'get', ['version' => $this->_apiversion
]);
229 throw new \
CRM_Core_Exception(
230 'Invalid getsingle result' . print_r($result, TRUE)
231 . "\n entity: $entity . \n params \n " . print_r($params, TRUE)
232 . "\n entities retrieved with blank params \n" . print_r($unfilteredResult, TRUE)
236 // @todo - have gone with the fn that unsets id? should we check id?
237 $this->checkArrayEquals($result, $checkAgainst);
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
247 * @param string $entity
248 * @param array $params
249 * @param string $type
250 * Per http://php.net/manual/en/function.gettype.php possible types.
259 * @throws \CRM_Core_Exception
261 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
263 'version' => $this->_apiversion
,
266 $result = $this->civicrm_api($entity, 'getvalue', $params);
267 if (is_array($result) && (!empty($result['is_error']) ||
isset($result['values']))) {
268 throw new \
CRM_Core_Exception('Invalid getvalue result' . print_r($result, TRUE));
271 if ($type === 'integer') {
272 // api seems to return integers as strings
273 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
276 $this->assertType($type, $result, "returned result should have been of type $type but was ");
283 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
287 * @param array $params
290 public function civicrm_api($entity, $action, $params = []) {
291 if (\CRM_Utils_Array
::value('version', $params) == 4) {
292 return $this->runApi4Legacy($entity, $action, $params);
294 return civicrm_api($entity, $action, $params);
298 * Emulate v3 syntax so we can run api3 tests on v4
302 * @param array $v3Params
304 * @throws \API_Exception
305 * @throws \CiviCRM_API3_Exception
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']);
317 if (!empty($v3Params['filters']['is_current']) ||
!empty($v3Params['isCurrent'])) {
318 $v4Params['current'] = TRUE;
320 $language = !empty($v3Params['options']['language']) ?
$v3Params['options']['language'] : \CRM_Utils_Array
::value('option.language', $v3Params);
322 $v4Params['language'] = $language;
324 $toRemove = ['option.', 'return', 'api.', 'format.'];
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;
333 unset($v3Params[$key]);
338 $v3Fields = civicrm_api3($v3Entity, 'getfields', ['action' => $v3Action])['values'];
341 foreach ($v3Params as $key => $val) {
342 if ($val === 'null') {
343 $v3Params[$key] = NULL;
347 if ($v4Entity == 'Setting') {
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'];
354 foreach (\CRM_Utils_Array
::value('filters', $v3Params, []) as $filter => $val) {
355 $v4Params['where'][] = [$filter, '=', $val];
358 if ($v3Action == 'create') {
361 if ($v3Action == 'revert') {
362 $v4Params['select'] = (array) $v3Params['name'];
364 if ($v3Action == 'getvalue') {
365 $options['return'] = [$v3Params['name'] => 1];
368 \CRM_Utils_Array
::remove($v3Params, 'domain_id', 'name');
371 \CRM_Utils_Array
::remove($v3Params, 'options', 'debug', 'version', 'sort', 'offset', 'rowCount', 'check_permissions', 'sequential', 'filters', 'isCurrent');
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']);
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]);
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]);
397 if (isset($options['return'][$name])) {
398 $options['return'][$v4FieldName] = 1;
399 unset($options['return'][$name]);
406 $v4Params['select'] = ['row_count'];
407 // No break - keep processing as get
411 // No break - keep processing as get
413 if ($options['return'] && $v3Action !== 'getcount') {
414 $v4Params['select'] = array_keys($options['return']);
416 if ($options['limit'] && $v4Entity != 'Setting') {
417 $v4Params['limit'] = $options['limit'];
419 if ($options['offset']) {
420 $v4Params['offset'] = $options['offset'];
422 if ($options['sort']) {
423 foreach (explode(',', $options['sort']) as $sort) {
424 list($sortField, $sortDir) = array_pad(explode(' ', trim($sort)), 2, 'ASC');
425 $v4Params['orderBy'][$sortField] = $sortDir;
431 if (empty($v3Params['values'])) {
432 $v4Action = 'delete';
435 $v4Params['records'] = $v3Params['values'];
437 unset($v3Params['values']);
442 if (!empty($v3Params['id'])) {
443 $v4Action = 'update';
444 $v4Params['where'][] = ['id', '=', $v3Params['id']];
447 $v4Params['values'] = $v3Params;
448 unset($v4Params['values']['id']);
452 if (!empty($v3Params['id'])) {
453 $v4Params['where'][] = ['id', '=', $v3Params['id']];
459 $v4Action = 'getFields';
461 'where' => [['name', '=', $v3Params['field']]],
462 'loadOptions' => TRUE,
467 $v4Action = 'getFields';
468 if (!empty($v3Params['action']) ||
!empty($v3Params['api_action'])) {
469 $v4Params['action'] = !empty($v3Params['action']) ?
$v3Params['action'] : $v3Params['api_action'];
471 $indexBy = !$sequential ?
'name' : NULL;
475 // Ensure this api4 entity/action exists
477 $actionInfo = \
civicrm_api4($v4Entity, 'getActions', ['checkPermissions' => FALSE, 'where' => [['name', '=', $v4Action]]]);
479 catch (NotImplementedException
$e) {
480 // For now we'll mark the test incomplete if a v4 entity doesn't exit yet
481 $this->markTestIncomplete($e->getMessage());
483 if (!isset($actionInfo[0])) {
484 throw new \
Exception("Api4 $v4Entity $v4Action does not exist.");
487 // Migrate special params like fix_address
488 foreach ($actionInfo[0]['params'] as $v4ParamName => $paramInfo) {
489 // camelCase in api4, lower_case in api3
490 $v3ParamName = strtolower(preg_replace('/(?=[A-Z])/', '_$0', $v4ParamName));
491 if (isset($v3Params[$v3ParamName])) {
492 $v4Params[$v4ParamName] = $v3Params[$v3ParamName];
493 unset($v3Params[$v3ParamName]);
494 if ($paramInfo['type'][0] == 'bool') {
495 $v4Params[$v4ParamName] = (bool) $v4Params[$v4ParamName];
500 // Build where clause for 'getcount', 'getsingle', 'getvalue', 'get' & 'replace'
501 if ($v4Action == 'get' ||
$v3Action == 'replace') {
502 foreach ($v3Params as $key => $val) {
504 if (is_array($val) && count($val) == 1 && array_intersect_key($val, array_flip(\CRM_Core_DAO
::acceptedSQLOperators()))) {
505 foreach ($val as $op => $newVal) {
509 $v4Params['where'][] = [$key, $op, $val];
514 $result = \
civicrm_api4($v4Entity, $v4Action, $v4Params, $indexBy);
516 catch (\Exception
$e) {
517 return $onlySuccess ?
0 : [
519 'error_message' => $e->getMessage(),
524 if (($v3Action == 'getsingle' ||
$v3Action == 'getvalue') && count($result) != 1) {
525 return $onlySuccess ?
0 : [
527 'error_message' => "Expected one $v4Entity but found " . count($result),
528 'count' => count($result),
536 if ($v3Action == 'getcount') {
537 return $result->count();
541 return $result->first()['id'];
544 if ($v3Action == 'getvalue' && $v4Entity == 'Setting') {
545 return \CRM_Utils_Array
::value('value', $result->first());
548 if ($v3Action == 'getvalue') {
549 return \CRM_Utils_Array
::value(array_keys($options['return'])[0], $result->first());
552 // Mimic api3 behavior when using 'replace' action to delete all
553 if ($v3Action == 'replace' && $v4Action == 'delete') {
554 $result->exchangeArray([]);
557 if ($v3Action == 'getoptions') {
560 'count' => $result['options'] ?
count($result['options']) : 0,
561 'values' => $result['options'] ?
: [],
566 // Emulate the weird return format of api3 settings
567 if (($v3Action == 'get' ||
$v3Action == 'create') && $v4Entity == 'Setting') {
569 foreach ($result as $item) {
570 $settings[$item['domain_id']][$item['name']] = $item['value'];
572 $result->exchangeArray($sequential ?
array_values($settings) : $settings);
575 foreach ($result as $index => $row) {
577 foreach ($chains as $key => $params) {
578 $result[$index][$key] = $this->runApi4LegacyChain($key, $params, $v4Entity, $row, $sequential);
580 // Resolve custom field names
581 foreach ($custom as $group => $fields) {
582 foreach ($fields as $field => $v3FieldName) {
583 if (isset($row["$group.$field"])) {
584 $result[$index][$v3FieldName] = $row["$group.$field"];
585 unset($result[$index]["$group.$field"]);
591 if ($v3Action == 'getsingle') {
592 return $result->first();
598 'count' => count($result),
599 'values' => (array) $result,
600 'id' => is_object($result) && count($result) == 1 ? \CRM_Utils_Array
::value('id', $result->first()) : NULL,
606 * @param mixed $params
607 * @param string $mainEntity
608 * @param array $result
609 * @param bool $sequential
611 * @throws \API_Exception
613 protected function runApi4LegacyChain($key, $params, $mainEntity, $result, $sequential) {
614 // Handle an array of multiple calls using recursion
615 if (is_array($params) && isset($params[0]) && is_array($params[0])) {
617 foreach ($params as $chain) {
618 $results[] = $this->runApi4LegacyChain($key, $chain, $mainEntity, $result, $sequential);
623 // Handle single api call
624 list(, $chainEntity, $chainAction) = explode('.', $key);
625 $lcChainEntity = \
_civicrm_api_get_entity_name_from_camel($chainEntity);
626 $chainEntity = self
::convertEntityNameToApi4($chainEntity);
627 $lcMainEntity = \
_civicrm_api_get_entity_name_from_camel($mainEntity);
628 $params = is_array($params) ?
$params : [];
630 // Api3 expects this to be inherited
631 $params +
= ['sequential' => $sequential];
633 // Replace $value.field_name
634 foreach ($params as $name => $param) {
635 if (is_string($param) && strpos($param, '$value.') === 0) {
636 $param = substr($param, 7);
637 $params[$name] = \CRM_Utils_Array
::value($param, $result);
642 $getFields = civicrm_api4($chainEntity, 'getFields', ['select' => ['name']], 'name');
644 catch (NotImplementedException
$e) {
645 $this->markTestIncomplete($e->getMessage());
648 // Emulate the string-fu guesswork that api3 does
649 if ($chainEntity == $mainEntity && empty($params['id']) && !empty($result['id'])) {
650 $params['id'] = $result['id'];
652 elseif (empty($params['id']) && !empty($result[$lcChainEntity . '_id'])) {
653 $params['id'] = $result[$lcChainEntity . '_id'];
655 elseif (!empty($result['id']) && isset($getFields[$lcMainEntity . '_id']) && empty($params[$lcMainEntity . '_id'])) {
656 $params[$lcMainEntity . '_id'] = $result['id'];
658 return $this->runApi4Legacy($chainEntity, $chainAction, $params);
662 * Fix the naming differences between api3 & api4 entities.
664 * @param string $legacyName
667 public static function convertEntityNameToApi4($legacyName) {
668 $api4Name = \CRM_Utils_String
::convertStringToCamel($legacyName);
673 return \CRM_Utils_Array
::value($api4Name, $map, $api4Name);