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