5 use Civi\API\Exception\NotImplementedException
;
7 require_once 'api/v3/utils.php';
12 * This trait defines a number of helper functions for testing APIv3. Commonly
13 * used helpers include `callAPISuccess()`, `callAPIFailure()`,
14 * `assertAPISuccess()`, and `assertAPIFailure()`.
16 * This trait is intended for use with PHPUnit-based test cases.
21 * Get the api versions to test.
25 public function versionThreeAndFour() {
33 * Api version - easier to override than just a define
36 protected $_apiversion = 3;
39 * Check that api returned 'is_error' => 1
40 * else provide full message
41 * @param array $result
43 * @param array $valuesToExclude
44 * @param string $prefix
45 * Extra test to add to message.
47 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = [], $prefix = '') {
48 $valuesToExclude = array_merge($valuesToExclude, ['debug', 'xdebug', 'sequential']);
49 foreach ($valuesToExclude as $value) {
50 if (isset($result[$value])) {
51 unset($result[$value]);
53 if (isset($expected[$value])) {
54 unset($expected[$value]);
57 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
61 * Check that a deleted item has been deleted.
66 public function assertAPIDeleted($entity, $id) {
67 $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0);
71 * Check that api returned 'is_error' => 1.
73 * @param array $apiResult
75 * @param string $prefix
76 * Extra test to add to message.
77 * @param null $expectedError
79 public function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
80 if (!empty($prefix)) {
83 if ($expectedError && !empty($apiResult['is_error'])) {
84 $this->assertStringContainsString($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
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']);
91 * Check that api returned 'is_error' => 0.
93 * @param array $apiResult
95 * @param string $prefix
96 * Extra test to add to message.
98 public function assertAPISuccess($apiResult, $prefix = '') {
99 if (!empty($prefix)) {
102 $errorMessage = empty($apiResult['error_message']) ?
'' : " " . $apiResult['error_message'];
104 if (!empty($apiResult['debug_information'])) {
105 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
107 if (!empty($apiResult['trace'])) {
108 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
110 $this->assertEmpty($apiResult['is_error'] ??
NULL, $prefix . $errorMessage);
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
121 * @param null $extraOutput
124 public function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
125 if (is_array($params)) {
127 'version' => $this->_apiversion
,
131 $result = $this->civicrm_api($entity, $action, $params);
133 catch (\API_Exception
$e) {
134 // api v4 call failed and threw an exception.
137 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success", $expectedErrorMessage);
142 * wrap api functions.
143 * so we can ensure they succeed & throw exceptions without litterering the test with checks
145 * @param string $entity
146 * @param string $action
147 * @param array $params
148 * @param mixed $checkAgainst
149 * Optional value to check result against, implemented for getvalue,.
150 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
151 * for getsingle the array is compared against an array passed in - the id is not compared (for
156 * @throws \CRM_Core_Exception
158 public function callAPISuccess($entity, $action, $params = [], $checkAgainst = NULL) {
159 $params = array_merge([
160 'version' => $this->_apiversion
,
165 switch (strtolower($action)) {
167 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
170 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
173 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
175 $result = $this->civicrm_api($entity, $action, $params);
176 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
181 * This function exists to wrap api getValue function & check the result
182 * so we can ensure they succeed & throw exceptions without littering the test with checks
183 * There is a type check in this
185 * @param string $entity
186 * @param array $params
191 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
193 'version' => $this->_apiversion
,
196 $result = $this->civicrm_api($entity, 'getcount', $params);
197 if (!is_int($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
198 $this->fail('Invalid getcount result : ' . print_r($result, TRUE) . ' type :' . gettype($result));
200 if (is_int($count)) {
201 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
207 * This function exists to wrap api getsingle function & check the result
208 * so we can ensure they succeed & throw exceptions without litterering the test with checks
210 * @param string $entity
211 * @param array $params
212 * @param array $checkAgainst
213 * Array to compare result against.
221 * @throws \CRM_Core_Exception
225 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
227 'version' => $this->_apiversion
,
229 $result = $this->civicrm_api($entity, 'getsingle', $params);
230 if (!is_array($result) ||
!empty($result['is_error']) ||
isset($result['values'])) {
231 $unfilteredResult = $this->civicrm_api($entity, 'get', ['version' => $this->_apiversion
]);
232 throw new \
CRM_Core_Exception(
233 'Invalid getsingle result' . print_r($result, TRUE)
234 . "\n entity: $entity . \n params \n " . print_r($params, TRUE)
235 . "\n entities retrieved with blank params \n" . print_r($unfilteredResult, TRUE)
239 // @todo - have gone with the fn that unsets id? should we check id?
240 $this->checkArrayEquals($result, $checkAgainst);
246 * This function exists to wrap api getValue function & check the result
247 * so we can ensure they succeed & throw exceptions without litterering the test with checks
248 * There is a type check in this
250 * @param string $entity
251 * @param array $params
252 * @param string $type
253 * Per http://php.net/manual/en/function.gettype.php possible types.
262 * @throws \CRM_Core_Exception
264 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
266 'version' => $this->_apiversion
,
268 $result = $this->civicrm_api($entity, 'getvalue', $params);
269 if (is_array($result) && (!empty($result['is_error']) ||
isset($result['values']))) {
270 throw new \
CRM_Core_Exception('Invalid getvalue result' . print_r($result, TRUE));
273 if ($type === 'integer') {
274 // api seems to return integers as strings
275 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
278 $this->assertType($type, $result, "returned result should have been of type $type but was ");
285 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
289 * @param array $params
292 public function civicrm_api($entity, $action, $params = []) {
293 if (($params['version'] ??
0) == 4) {
294 return $this->runApi4Legacy($entity, $action, $params);
296 return civicrm_api($entity, $action, $params);
300 * Emulate v3 syntax so we can run api3 tests on v4
304 * @param array $v3Params
306 * @throws \API_Exception
307 * @throws \CiviCRM_API3_Exception
310 public function runApi4Legacy($v3Entity, $v3Action, $v3Params = []) {
311 $v4Entity = \CRM_Core_DAO_AllCoreTables
::convertEntityNameToCamel($v3Entity);
312 $v4Action = $v3Action = strtolower($v3Action);
313 $v4Params = ['checkPermissions' => isset($v3Params['check_permissions']) ?
(bool) $v3Params['check_permissions'] : FALSE];
314 $sequential = !empty($v3Params['sequential']);
315 $options = \
_civicrm_api3_get_options_from_params($v3Params, in_array($v4Entity, ['Contact', 'Participant', 'Event', 'Group', 'Contribution', 'Membership']));
316 $indexBy = in_array($v3Action, ['get', 'create', 'replace']) && !$sequential ?
'id' : NULL;
317 $onlyId = !empty($v3Params['format.only_id']);
318 $onlySuccess = !empty($v3Params['format.is_success']);
319 if (!empty($v3Params['filters']['is_current']) ||
!empty($v3Params['isCurrent'])) {
320 $v4Params['current'] = TRUE;
322 $language = $v3Params['options']['language'] ??
$v3Params['option.language'] ??
NULL;
324 $v4Params['language'] = $language;
326 $toRemove = ['option.', 'return', 'api.', 'format.'];
327 $chains = $joins = $custom = [];
328 foreach ($v3Params as $key => $val) {
329 foreach ($toRemove as $remove) {
330 if (strpos($key, $remove) === 0) {
331 if ($remove == 'api.') {
332 $chains[$key] = $val;
334 unset($v3Params[$key]);
339 $v3Fields = civicrm_api3($v3Entity, 'getfields', ['action' => $v3Action])['values'];
342 foreach ($v3Params as $key => $val) {
343 if ($val === 'null') {
344 $v3Params[$key] = NULL;
348 if ($v4Entity == 'Setting') {
350 $v4Params['domainId'] = $v3Params['domain_id'] ??
NULL;
351 if ($v3Action == 'getfields') {
352 if (!empty($v3Params['name'])) {
353 $v3Params['filters']['name'] = $v3Params['name'];
355 foreach ($v3Params['filters'] ??
[] as $filter => $val) {
356 $v4Params['where'][] = [$filter, '=', $val];
359 if ($v3Action == 'create') {
362 if ($v3Action == 'revert') {
363 $v4Params['select'] = (array) $v3Params['name'];
365 if ($v3Action == 'getvalue') {
366 $options['return'] = [$v3Params['name'] => 1];
369 \CRM_Utils_Array
::remove($v3Params, 'domain_id', 'name');
372 \CRM_Utils_Array
::remove($v3Params, 'options', 'debug', 'version', 'sort', 'offset', 'rowCount', 'check_permissions', 'sequential', 'filters', 'isCurrent');
374 // Work around ugly hack in v3 Domain api
375 if ($v4Entity == 'Domain') {
376 $v3Fields['version'] = ['name' => 'version', 'api.aliases' => ['domain_version']];
377 unset($v3Fields['domain_version']);
380 foreach ($v3Fields as $name => $field) {
381 // Resolve v3 aliases
382 foreach ($field['api.aliases'] ??
[] as $alias) {
383 if (isset($v3Params[$alias])) {
384 $v3Params[$field['name']] = $v3Params[$alias];
385 unset($v3Params[$alias]);
388 // Convert custom field names
389 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
390 // Strictly speaking, using titles instead of names is incorrect, but it works for
391 // unit tests where names and titles are identical and saves an extra db lookup.
392 $custom[$field['groupTitle']][$field['title']] = $name;
393 $v4FieldName = $field['groupTitle'] . '.' . $field['title'];
394 if (isset($v3Params[$name])) {
395 $v3Params[$v4FieldName] = $v3Params[$name];
396 unset($v3Params[$name]);
398 if (isset($options['return'][$name])) {
399 $options['return'][$v4FieldName] = 1;
400 unset($options['return'][$name]);
404 if ($name === 'option_group_id' && isset($v3Params[$name]) && !is_numeric($v3Params[$name])) {
405 // This is a per field hack (bad) but we can't solve everything at once
406 // & a cleverer way turned out to be too much for this round.
407 // Being in the test class it's tested....
408 $v3Params['option_group.name'] = $v3Params['option_group_id'];
409 unset($v3Params['option_group_id']);
411 if (isset($field['pseudoconstant'], $v3Params[$name]) && $field['type'] === \CRM_Utils_Type
::T_INT
&& !is_numeric($v3Params[$name]) && is_string($v3Params[$name])) {
412 $v3Params[$name] = \CRM_Core_PseudoConstant
::getKey(\CRM_Core_DAO_AllCoreTables
::getFullName($v4Entity), $name, $v3Params[$name]);
418 $v4Params['select'] = ['row_count'];
419 // No break - keep processing as get
423 // No break - keep processing as get
425 if ($options['return'] && $v3Action !== 'getcount') {
426 $v4Params['select'] = array_keys($options['return']);
427 // Ensure id field is returned as v3 always expects it
428 if ($v4Entity != 'Setting' && !in_array('id', $v4Params['select'])) {
429 $v4Params['select'][] = 'id';
431 // Convert join syntax
432 foreach ($v4Params['select'] as $idx => $select) {
433 if (strstr($select, '_id.')) {
434 $joins[$select] = $v4Params['select'][$idx] = str_replace('_id.', '.', $select);
438 if ($options['limit'] && $v4Entity != 'Setting') {
439 $v4Params['limit'] = $options['limit'];
441 if ($options['offset']) {
442 $v4Params['offset'] = $options['offset'];
444 if ($options['sort']) {
445 foreach (explode(',', $options['sort']) as $sort) {
446 [$sortField, $sortDir] = array_pad(explode(' ', trim($sort)), 2, 'ASC');
447 $v4Params['orderBy'][$sortField] = $sortDir;
453 if (empty($v3Params['values'])) {
454 $v4Action = 'delete';
457 $v4Params['records'] = $v3Params['values'];
459 unset($v3Params['values']);
464 if (!empty($v3Params['id'])) {
465 $v4Action = 'update';
466 $v4Params['where'][] = ['id', '=', $v3Params['id']];
469 $v4Params['values'] = $v3Params;
470 unset($v4Params['values']['id']);
474 if (isset($v3Params['id'])) {
475 $v4Params['where'][] = ['id', '=', $v3Params['id']];
481 $v4Action = 'getFields';
483 'where' => [['name', '=', $v3Params['field']]],
484 'loadOptions' => TRUE,
489 $v4Action = 'getFields';
490 if (!empty($v3Params['action']) ||
!empty($v3Params['api_action'])) {
491 $v4Params['action'] = !empty($v3Params['action']) ?
$v3Params['action'] : $v3Params['api_action'];
493 $indexBy = !$sequential ?
'name' : NULL;
497 // Ensure this api4 entity/action exists
499 $actionInfo = \
civicrm_api4($v4Entity, 'getActions', ['checkPermissions' => FALSE, 'where' => [['name', '=', $v4Action]]]);
501 catch (NotImplementedException
$e) {
502 // For now we'll mark the test incomplete if a v4 entity doesn't exit yet
503 $this->markTestIncomplete($e->getMessage());
505 if (!isset($actionInfo[0])) {
506 throw new \
Exception("Api4 $v4Entity $v4Action does not exist.");
509 // Migrate special params like fix_address
510 foreach ($actionInfo[0]['params'] as $v4ParamName => $paramInfo) {
511 // camelCase in api4, lower_case in api3
512 $v3ParamName = strtolower(preg_replace('/(?=[A-Z])/', '_$0', $v4ParamName));
513 if (isset($v3Params[$v3ParamName])) {
514 $v4Params[$v4ParamName] = $v3Params[$v3ParamName];
515 unset($v3Params[$v3ParamName]);
516 if ($paramInfo['type'][0] == 'bool') {
517 $v4Params[$v4ParamName] = (bool) $v4Params[$v4ParamName];
522 // Build where clause for 'getcount', 'getsingle', 'getvalue', 'get' & 'replace'
523 if ($v4Action == 'get' ||
$v3Action == 'replace') {
524 foreach ($v3Params as $key => $val) {
526 if (is_array($val) && count($val) == 1 && array_intersect_key($val, array_flip(\CRM_Core_DAO
::acceptedSQLOperators()))) {
527 foreach ($val as $op => $newVal) {
531 $v4Params['where'][] = [$key, $op, $val];
536 $result = \
civicrm_api4($v4Entity, $v4Action, $v4Params, $indexBy);
538 catch (\Exception
$e) {
539 return $onlySuccess ?
0 : [
541 'error_message' => $e->getMessage(),
546 if (($v3Action == 'getsingle' ||
$v3Action == 'getvalue' ||
$v3Action == 'delete') && count($result) != 1) {
547 return $onlySuccess ?
0 : [
549 'error_message' => "Expected one $v4Entity but found " . count($result),
550 'count' => count($result),
558 if ($v3Action == 'getcount') {
559 return $result->count();
563 return $result->first()['id'];
566 if ($v3Action == 'getvalue' && $v4Entity == 'Setting') {
567 return $result->first()['value'] ??
NULL;
570 if ($v3Action == 'getvalue') {
571 $returnKey = array_keys($options['return'])[0];
572 return $result->first()[$returnKey] ??
NULL;
575 // Mimic api3 behavior when using 'replace' action to delete all
576 if ($v3Action == 'replace' && $v4Action == 'delete') {
577 $result->exchangeArray([]);
580 if ($v3Action == 'getoptions') {
583 'count' => $result['options'] ?
count($result['options']) : 0,
584 'values' => $result['options'] ?
: [],
589 // Emulate the weird return format of api3 settings
590 if (($v3Action == 'get' ||
$v3Action == 'create') && $v4Entity == 'Setting') {
592 foreach ($result as $item) {
593 $settings[$item['domain_id']][$item['name']] = $item['value'];
595 $result->exchangeArray($sequential ?
array_values($settings) : $settings);
598 foreach ($result as $index => $row) {
600 foreach ($chains as $key => $params) {
601 $result[$index][$key] = $this->runApi4LegacyChain($key, $params, $v4Entity, $row, $sequential);
603 // Convert join format
604 foreach ($joins as $api3Key => $api4Key) {
605 $result[$index][$api3Key] = $result[$index][$api4Key] ??
NULL;
607 // Resolve custom field names
608 foreach ($custom as $group => $fields) {
609 foreach ($fields as $field => $v3FieldName) {
610 if (isset($row["$group.$field"])) {
611 $result[$index][$v3FieldName] = $row["$group.$field"];
612 unset($result[$index]["$group.$field"]);
618 if ($v3Action == 'getsingle') {
619 return $result->first();
625 'count' => count($result),
626 'values' => (array) $result,
627 'id' => is_object($result) && count($result) == 1 ?
($result->first()['id'] ??
NULL) : NULL,
633 * @param mixed $params
634 * @param string $mainEntity
635 * @param array $result
636 * @param bool $sequential
638 * @throws \API_Exception
640 protected function runApi4LegacyChain($key, $params, $mainEntity, $result, $sequential) {
641 // Handle an array of multiple calls using recursion
642 if (is_array($params) && isset($params[0]) && is_array($params[0])) {
644 foreach ($params as $chain) {
645 $results[] = $this->runApi4LegacyChain($key, $chain, $mainEntity, $result, $sequential);
650 // Handle single api call
651 list(, $chainEntity, $chainAction) = explode('.', $key);
652 $lcChainEntity = \CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($chainEntity);
653 $chainEntity = \CRM_Core_DAO_AllCoreTables
::convertEntityNameToCamel($chainEntity);
654 $lcMainEntity = \CRM_Core_DAO_AllCoreTables
::convertEntityNameToLower($mainEntity);
655 $params = is_array($params) ?
$params : [];
657 // Api3 expects this to be inherited
658 $params +
= ['sequential' => $sequential];
660 // Replace $value.field_name
661 foreach ($params as $name => $param) {
662 if (is_string($param) && strpos($param, '$value.') === 0) {
663 $param = substr($param, 7);
664 $params[$name] = $result[$param] ??
NULL;
669 $getFields = civicrm_api4($chainEntity, 'getFields', ['select' => ['name']], 'name');
671 catch (NotImplementedException
$e) {
672 $this->markTestIncomplete($e->getMessage());
675 // Emulate the string-fu guesswork that api3 does
676 if ($chainEntity == $mainEntity && empty($params['id']) && !empty($result['id'])) {
677 $params['id'] = $result['id'];
679 elseif (empty($params['id']) && !empty($result[$lcChainEntity . '_id'])) {
680 $params['id'] = $result[$lcChainEntity . '_id'];
682 elseif (!empty($result['id']) && isset($getFields[$lcMainEntity . '_id']) && empty($params[$lcMainEntity . '_id'])) {
683 $params[$lcMainEntity . '_id'] = $result['id'];
685 return $this->runApi4Legacy($chainEntity, $chainAction, $params);