Merge pull request #15343 from colemanw/upgrader
[civicrm-core.git] / Civi / Test / Api3TestTrait.php
1 <?php
2
3 namespace Civi\Test;
4
5 use Civi\API\Exception\NotImplementedException;
6
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
19 /**
20 * Get the api versions to test.
21 *
22 * @return array
23 */
24 public function versionThreeAndFour() {
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;
31 }
32
33 /**
34 * Api version - easier to override than just a define
35 * @var int
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 */
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]);
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) {
68 $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0);
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'])) {
85 $this->assertContains($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
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 }
111 $this->assertEmpty(\CRM_Utils_Array::value('is_error', $apiResult), $prefix . $errorMessage);
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)) {
127 $params += [
128 'version' => $this->_apiversion,
129 ];
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
150 */
151 public function callAPISuccess($entity, $action, $params = [], $checkAgainst = NULL) {
152 $params = array_merge([
153 'version' => $this->_apiversion,
154 'debug' => 1,
155 ],
156 $params
157 );
158 switch (strtolower($action)) {
159 case 'getvalue':
160 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
161
162 case 'getsingle':
163 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
164
165 case 'getcount':
166 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
167 }
168 $result = $this->civicrm_api($entity, $action, $params);
169 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
170 return $result;
171 }
172
173 /**
174 * This function exists to wrap api getValue function & check the result
175 * so we can ensure they succeed & throw exceptions without litterering the test with checks
176 * There is a type check in this
177 *
178 * @param string $entity
179 * @param array $params
180 * @param int $count
181 *
182 * @throws \CRM_Core_Exception
183 *
184 * @return array|int
185 */
186 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
187 $params += [
188 'version' => $this->_apiversion,
189 'debug' => 1,
190 ];
191 $result = $this->civicrm_api($entity, 'getcount', $params);
192 if (!is_int($result) || !empty($result['is_error']) || isset($result['values'])) {
193 throw new \CRM_Core_Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
194 }
195 if (is_int($count)) {
196 $this->assertEquals($count, $result, "incorrect count returned from $entity getcount");
197 }
198 return $result;
199 }
200
201 /**
202 * This function exists to wrap api getsingle function & check the result
203 * so we can ensure they succeed & throw exceptions without litterering the test with checks
204 *
205 * @param string $entity
206 * @param array $params
207 * @param array $checkAgainst
208 * Array to compare result against.
209 * - boolean
210 * - integer
211 * - double
212 * - string
213 * - array
214 * - object
215 *
216 * @throws \CRM_Core_Exception
217 *
218 * @return array|int
219 */
220 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
221 $params += [
222 'version' => $this->_apiversion,
223 ];
224 $result = $this->civicrm_api($entity, 'getsingle', $params);
225 if (!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
226 $unfilteredResult = $this->civicrm_api($entity, 'get', ['version' => $this->_apiversion]);
227 throw new \CRM_Core_Exception(
228 'Invalid getsingle result' . print_r($result, TRUE)
229 . "\n entity: $entity . \n params \n " . print_r($params, TRUE)
230 . "\n entities retrieved with blank params \n" . print_r($unfilteredResult, TRUE)
231 );
232 }
233 if ($checkAgainst) {
234 // @todo - have gone with the fn that unsets id? should we check id?
235 $this->checkArrayEquals($result, $checkAgainst);
236 }
237 return $result;
238 }
239
240 /**
241 * This function exists to wrap api getValue function & check the result
242 * so we can ensure they succeed & throw exceptions without litterering the test with checks
243 * There is a type check in this
244 *
245 * @param string $entity
246 * @param array $params
247 * @param string $type
248 * Per http://php.net/manual/en/function.gettype.php possible types.
249 * - boolean
250 * - integer
251 * - double
252 * - string
253 * - array
254 * - object
255 *
256 * @return array|int
257 * @throws \CRM_Core_Exception
258 */
259 public function callAPISuccessGetValue($entity, $params, $type = NULL) {
260 $params += [
261 'version' => $this->_apiversion,
262 'debug' => 1,
263 ];
264 $result = $this->civicrm_api($entity, 'getvalue', $params);
265 if (is_array($result) && (!empty($result['is_error']) || isset($result['values']))) {
266 throw new \CRM_Core_Exception('Invalid getvalue result' . print_r($result, TRUE));
267 }
268 if ($type) {
269 if ($type === 'integer') {
270 // api seems to return integers as strings
271 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
272 }
273 else {
274 $this->assertType($type, $result, "returned result should have been of type $type but was ");
275 }
276 }
277 return $result;
278 }
279
280 /**
281 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
282 *
283 * @param $entity
284 * @param $action
285 * @param array $params
286 * @return array|int
287 */
288 public function civicrm_api($entity, $action, $params = []) {
289 if (\CRM_Utils_Array::value('version', $params) == 4) {
290 return $this->runApi4Legacy($entity, $action, $params);
291 }
292 return civicrm_api($entity, $action, $params);
293 }
294
295 /**
296 * Emulate v3 syntax so we can run api3 tests on v4
297 *
298 * @param $v3Entity
299 * @param $v3Action
300 * @param array $v3Params
301 * @return array|int
302 * @throws \API_Exception
303 * @throws \CiviCRM_API3_Exception
304 * @throws \Exception
305 */
306 public function runApi4Legacy($v3Entity, $v3Action, $v3Params = []) {
307 $v4Entity = self::convertEntityNameToApi4($v3Entity);
308 $v4Action = $v3Action = strtolower($v3Action);
309 $v4Params = ['checkPermissions' => isset($v3Params['check_permissions']) ? (bool) $v3Params['check_permissions'] : FALSE];
310 $sequential = !empty($v3Params['sequential']);
311 $options = \_civicrm_api3_get_options_from_params($v3Params, in_array($v4Entity, ['Contact', 'Participant', 'Event', 'Group', 'Contribution', 'Membership']));
312 $indexBy = in_array($v3Action, ['get', 'create', 'replace']) && !$sequential ? 'id' : NULL;
313 $onlyId = !empty($v3Params['format.only_id']);
314 $onlySuccess = !empty($v3Params['format.is_success']);
315 if (!empty($v3Params['filters']['is_current']) || !empty($v3Params['isCurrent'])) {
316 $v4Params['current'] = TRUE;
317 }
318 $language = !empty($v3Params['options']['language']) ? $v3Params['options']['language'] : \CRM_Utils_Array::value('option.language', $v3Params);
319 if ($language) {
320 $v4Params['language'] = $language;
321 }
322 $toRemove = ['option.', 'return', 'api.', 'format.'];
323 $chains = [];
324 $custom = [];
325 foreach ($v3Params as $key => $val) {
326 foreach ($toRemove as $remove) {
327 if (strpos($key, $remove) === 0) {
328 if ($remove == 'api.') {
329 $chains[$key] = $val;
330 }
331 unset($v3Params[$key]);
332 }
333 }
334 }
335
336 $v3Fields = civicrm_api3($v3Entity, 'getfields', ['action' => $v3Action])['values'];
337
338 // Fix 'null'
339 foreach ($v3Params as $key => $val) {
340 if ($val === 'null') {
341 $v3Params[$key] = NULL;
342 }
343 }
344
345 if ($v4Entity == 'Setting') {
346 $indexBy = NULL;
347 $v4Params['domainId'] = \CRM_Utils_Array::value('domain_id', $v3Params);
348 if ($v3Action == 'getfields') {
349 if (!empty($v3Params['name'])) {
350 $v3Params['filters']['name'] = $v3Params['name'];
351 }
352 foreach (\CRM_Utils_Array::value('filters', $v3Params, []) as $filter => $val) {
353 $v4Params['where'][] = [$filter, '=', $val];
354 }
355 }
356 if ($v3Action == 'create') {
357 $v4Action = 'set';
358 }
359 if ($v3Action == 'revert') {
360 $v4Params['select'] = (array) $v3Params['name'];
361 }
362 if ($v3Action == 'getvalue') {
363 $options['return'] = [$v3Params['name'] => 1];
364 $v3Params = [];
365 }
366 \CRM_Utils_Array::remove($v3Params, 'domain_id', 'name');
367 }
368
369 \CRM_Utils_Array::remove($v3Params, 'options', 'debug', 'version', 'sort', 'offset', 'rowCount', 'check_permissions', 'sequential', 'filters', 'isCurrent');
370
371 // Work around ugly hack in v3 Domain api
372 if ($v4Entity == 'Domain') {
373 $v3Fields['version'] = ['name' => 'version', 'api.aliases' => ['domain_version']];
374 unset($v3Fields['domain_version']);
375 }
376
377 foreach ($v3Fields as $name => $field) {
378 // Resolve v3 aliases
379 foreach (\CRM_Utils_Array::value('api.aliases', $field, []) as $alias) {
380 if (isset($v3Params[$alias])) {
381 $v3Params[$field['name']] = $v3Params[$alias];
382 unset($v3Params[$alias]);
383 }
384 }
385 // Convert custom field names
386 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
387 // Strictly speaking, using titles instead of names is incorrect, but it works for
388 // unit tests where names and titles are identical and saves an extra db lookup.
389 $custom[$field['groupTitle']][$field['title']] = $name;
390 $v4FieldName = $field['groupTitle'] . '.' . $field['title'];
391 if (isset($v3Params[$name])) {
392 $v3Params[$v4FieldName] = $v3Params[$name];
393 unset($v3Params[$name]);
394 }
395 if (isset($options['return'][$name])) {
396 $options['return'][$v4FieldName] = 1;
397 unset($options['return'][$name]);
398 }
399 }
400 }
401
402 switch ($v3Action) {
403 case 'getcount':
404 $v4Params['select'] = ['row_count'];
405 // No break - keep processing as get
406 case 'getsingle':
407 case 'getvalue':
408 $v4Action = 'get';
409 // No break - keep processing as get
410 case 'get':
411 if ($options['return'] && $v3Action !== 'getcount') {
412 $v4Params['select'] = array_keys($options['return']);
413 }
414 if ($options['limit'] && $v4Entity != 'Setting') {
415 $v4Params['limit'] = $options['limit'];
416 }
417 if ($options['offset']) {
418 $v4Params['offset'] = $options['offset'];
419 }
420 if ($options['sort']) {
421 foreach (explode(',', $options['sort']) as $sort) {
422 list($sortField, $sortDir) = array_pad(explode(' ', trim($sort)), 2, 'ASC');
423 $v4Params['orderBy'][$sortField] = $sortDir;
424 }
425 }
426 break;
427
428 case 'replace':
429 if (empty($v3Params['values'])) {
430 $v4Action = 'delete';
431 }
432 else {
433 $v4Params['records'] = $v3Params['values'];
434 }
435 unset($v3Params['values']);
436 break;
437
438 case 'create':
439 case 'update':
440 if (!empty($v3Params['id'])) {
441 $v4Action = 'update';
442 $v4Params['where'][] = ['id', '=', $v3Params['id']];
443 }
444
445 $v4Params['values'] = $v3Params;
446 unset($v4Params['values']['id']);
447 break;
448
449 case 'delete':
450 if (!empty($v3Params['id'])) {
451 $v4Params['where'][] = ['id', '=', $v3Params['id']];
452 }
453 break;
454
455 case 'getoptions':
456 $indexBy = 0;
457 $v4Action = 'getFields';
458 $v4Params += [
459 'where' => [['name', '=', $v3Params['field']]],
460 'loadOptions' => TRUE,
461 ];
462 break;
463
464 case 'getfields':
465 $v4Action = 'getFields';
466 if (!empty($v3Params['action']) || !empty($v3Params['api_action'])) {
467 $v4Params['action'] = !empty($v3Params['action']) ? $v3Params['action'] : $v3Params['api_action'];
468 }
469 $indexBy = !$sequential ? 'name' : NULL;
470 break;
471 }
472
473 // Ensure this api4 entity/action exists
474 try {
475 $actionInfo = \civicrm_api4($v4Entity, 'getActions', ['checkPermissions' => FALSE, 'where' => [['name', '=', $v4Action]]]);
476 }
477 catch (NotImplementedException $e) {
478 // For now we'll mark the test incomplete if a v4 entity doesn't exit yet
479 $this->markTestIncomplete($e->getMessage());
480 }
481 if (!isset($actionInfo[0])) {
482 throw new \Exception("Api4 $v4Entity $v4Action does not exist.");
483 }
484
485 // Migrate special params like fix_address
486 foreach ($actionInfo[0]['params'] as $v4ParamName => $paramInfo) {
487 // camelCase in api4, lower_case in api3
488 $v3ParamName = strtolower(preg_replace('/(?=[A-Z])/', '_$0', $v4ParamName));
489 if (isset($v3Params[$v3ParamName])) {
490 $v4Params[$v4ParamName] = $v3Params[$v3ParamName];
491 unset($v3Params[$v3ParamName]);
492 if ($paramInfo['type'][0] == 'bool') {
493 $v4Params[$v4ParamName] = (bool) $v4Params[$v4ParamName];
494 }
495 }
496 }
497
498 // Build where clause for 'getcount', 'getsingle', 'getvalue', 'get' & 'replace'
499 if ($v4Action == 'get' || $v3Action == 'replace') {
500 foreach ($v3Params as $key => $val) {
501 $op = '=';
502 if (is_array($val) && count($val) == 1 && array_intersect_key($val, array_flip(\CRM_Core_DAO::acceptedSQLOperators()))) {
503 foreach ($val as $op => $newVal) {
504 $val = $newVal;
505 }
506 }
507 $v4Params['where'][] = [$key, $op, $val];
508 }
509 }
510
511 try {
512 $result = \civicrm_api4($v4Entity, $v4Action, $v4Params, $indexBy);
513 }
514 catch (\Exception $e) {
515 return $onlySuccess ? 0 : [
516 'is_error' => 1,
517 'error_message' => $e->getMessage(),
518 'version' => 4,
519 ];
520 }
521
522 if (($v3Action == 'getsingle' || $v3Action == 'getvalue') && count($result) != 1) {
523 return $onlySuccess ? 0 : [
524 'is_error' => 1,
525 'error_message' => "Expected one $v4Entity but found " . count($result),
526 'count' => count($result),
527 ];
528 }
529
530 if ($onlySuccess) {
531 return 1;
532 }
533
534 if ($v3Action == 'getcount') {
535 return $result->count();
536 }
537
538 if ($onlyId) {
539 return $result->first()['id'];
540 }
541
542 if ($v3Action == 'getvalue' && $v4Entity == 'Setting') {
543 return \CRM_Utils_Array::value('value', $result->first());
544 }
545
546 if ($v3Action == 'getvalue') {
547 return \CRM_Utils_Array::value(array_keys($options['return'])[0], $result->first());
548 }
549
550 // Mimic api3 behavior when using 'replace' action to delete all
551 if ($v3Action == 'replace' && $v4Action == 'delete') {
552 $result->exchangeArray([]);
553 }
554
555 if ($v3Action == 'getoptions') {
556 return [
557 'is_error' => 0,
558 'count' => $result['options'] ? count($result['options']) : 0,
559 'values' => $result['options'] ?: [],
560 'version' => 4,
561 ];
562 }
563
564 // Emulate the weird return format of api3 settings
565 if (($v3Action == 'get' || $v3Action == 'create') && $v4Entity == 'Setting') {
566 $settings = [];
567 foreach ($result as $item) {
568 $settings[$item['domain_id']][$item['name']] = $item['value'];
569 }
570 $result->exchangeArray($sequential ? array_values($settings) : $settings);
571 }
572
573 foreach ($result as $index => $row) {
574 // Run chains
575 foreach ($chains as $key => $params) {
576 $result[$index][$key] = $this->runApi4LegacyChain($key, $params, $v4Entity, $row, $sequential);
577 }
578 // Resolve custom field names
579 foreach ($custom as $group => $fields) {
580 if (isset($row[$group])) {
581 foreach ($fields as $field => $v3FieldName) {
582 if (isset($row[$group][$field])) {
583 $result[$index][$v3FieldName] = $row[$group][$field];
584 }
585 }
586 unset($result[$index][$group]);
587 }
588 }
589 }
590
591 if ($v3Action == 'getsingle') {
592 return $result->first();
593 }
594
595 return [
596 'is_error' => 0,
597 'version' => 4,
598 'count' => count($result),
599 'values' => (array) $result,
600 'id' => is_object($result) && count($result) == 1 ? \CRM_Utils_Array::value('id', $result->first()) : NULL,
601 ];
602 }
603
604 /**
605 * @param string $key
606 * @param mixed $params
607 * @param string $mainEntity
608 * @param array $result
609 * @param bool $sequential
610 * @return array
611 * @throws \API_Exception
612 */
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])) {
616 $results = [];
617 foreach ($params as $chain) {
618 $results[] = $this->runApi4LegacyChain($key, $chain, $mainEntity, $result, $sequential);
619 }
620 return $results;
621 }
622
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 : [];
629
630 // Api3 expects this to be inherited
631 $params += ['sequential' => $sequential];
632
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);
638 }
639 }
640
641 try {
642 $getFields = civicrm_api4($chainEntity, 'getFields', ['select' => ['name']], 'name');
643 }
644 catch (NotImplementedException $e) {
645 $this->markTestIncomplete($e->getMessage());
646 }
647
648 // Emulate the string-fu guesswork that api3 does
649 if ($chainEntity == $mainEntity && empty($params['id']) && !empty($result['id'])) {
650 $params['id'] = $result['id'];
651 }
652 elseif (empty($params['id']) && !empty($result[$lcChainEntity . '_id'])) {
653 $params['id'] = $result[$lcChainEntity . '_id'];
654 }
655 elseif (!empty($result['id']) && isset($getFields[$lcMainEntity . '_id']) && empty($params[$lcMainEntity . '_id'])) {
656 $params[$lcMainEntity . '_id'] = $result['id'];
657 }
658 return $this->runApi4Legacy($chainEntity, $chainAction, $params);
659 }
660
661 /**
662 * Fix the naming differences between api3 & api4 entities.
663 *
664 * @param string $legacyName
665 * @return string
666 */
667 public static function convertEntityNameToApi4($legacyName) {
668 $api4Name = \CRM_Utils_String::convertStringToCamel($legacyName);
669 $map = [
670 'Im' => 'IM',
671 'Acl' => 'ACL',
672 ];
673 return \CRM_Utils_Array::value($api4Name, $map, $api4Name);
674 }
675
676 }