Merge pull request #14519 from colemanw/submitOnce
[civicrm-core.git] / Civi / Test / Api3TestTrait.php
CommitLineData
30f5345c
TO
1<?php
2
3namespace Civi\Test;
4
62950ef9
CW
5use 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 */
17trait Api3TestTrait {
18
62950ef9
CW
19 /**
20 * Get the api versions to test.
21 *
22 * @return array
23 */
24 public function versionThreeAndFour() {
25 return [[3], [4]];
26 }
27
30f5345c
TO
28 /**
29 * Api version - easier to override than just a define
34f3bbd9 30 * @var int
30f5345c
TO
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 */
c64f69d9
CW
43 public function assertAPIArrayComparison($result, $expected, $valuesToExclude = [], $prefix = '') {
44 $valuesToExclude = array_merge($valuesToExclude, ['debug', 'xdebug', 'sequential']);
30f5345c
TO
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) {
c64f69d9 63 $this->callAPISuccess($entity, 'getcount', ['id' => $id], 0);
30f5345c
TO
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'])) {
62950ef9 80 $this->assertContains($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix);
30f5345c
TO
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 }
62950ef9 106 $this->assertEmpty(\CRM_Utils_Array::value('is_error', $apiResult), $prefix . $errorMessage);
30f5345c
TO
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)) {
c64f69d9 122 $params += [
30f5345c 123 'version' => $this->_apiversion,
c64f69d9 124 ];
30f5345c
TO
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 */
62950ef9 146 public function callAPISuccess($entity, $action, $params = [], $checkAgainst = NULL) {
c64f69d9 147 $params = array_merge([
30f5345c
TO
148 'version' => $this->_apiversion,
149 'debug' => 1,
c64f69d9 150 ],
30f5345c
TO
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
023f9e8a 172 *
30f5345c
TO
173 * @param string $entity
174 * @param array $params
023f9e8a 175 * @param int $count
176 *
177 * @throws \CRM_Core_Exception
178 *
30f5345c
TO
179 * @return array|int
180 */
181 public function callAPISuccessGetCount($entity, $params, $count = NULL) {
c64f69d9 182 $params += [
30f5345c
TO
183 'version' => $this->_apiversion,
184 'debug' => 1,
c64f69d9 185 ];
30f5345c
TO
186 $result = $this->civicrm_api($entity, 'getcount', $params);
187 if (!is_int($result) || !empty($result['is_error']) || isset($result['values'])) {
023f9e8a 188 throw new \CRM_Core_Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
30f5345c
TO
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 *
023f9e8a 211 * @throws \CRM_Core_Exception
212 *
30f5345c
TO
213 * @return array|int
214 */
215 public function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
c64f69d9 216 $params += [
30f5345c 217 'version' => $this->_apiversion,
c64f69d9 218 ];
30f5345c
TO
219 $result = $this->civicrm_api($entity, 'getsingle', $params);
220 if (!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
023f9e8a 221 $unfilteredResult = $this->civicrm_api($entity, 'get', ['version' => $this->_apiversion]);
222 throw new \CRM_Core_Exception(
cb4e7d31 223 'Invalid getsingle result' . print_r($result, TRUE)
224 . "\n entity: $entity . \n params \n " . print_r($params, TRUE)
34f3bbd9 225 . "\n entities retrieved with blank params \n" . print_r($unfilteredResult, TRUE)
cb4e7d31 226 );
30f5345c
TO
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) {
c64f69d9 254 $params += [
30f5345c
TO
255 'version' => $this->_apiversion,
256 'debug' => 1,
c64f69d9 257 ];
30f5345c 258 $result = $this->civicrm_api($entity, 'getvalue', $params);
1bf00882
PN
259 if (is_array($result) && (!empty($result['is_error']) || isset($result['values']))) {
260 throw new \Exception('Invalid getvalue result' . print_r($result, TRUE));
261 }
30f5345c
TO
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 */
62950ef9
CW
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 }
30f5345c
TO
286 return civicrm_api($entity, $action, $params);
287 }
288
62950ef9
CW
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($params['isCurrent'])) {
310 $v4Params['current'] = TRUE;
311 }
312 $toRemove = ['option.', 'return', 'api.', 'format.'];
313 $chains = [];
314 $custom = [];
315 foreach ($v3Params as $key => $val) {
316 foreach ($toRemove as $remove) {
317 if (strpos($key, $remove) === 0) {
318 if ($remove == 'api.') {
319 $chains[$key] = $val;
320 }
321 unset($v3Params[$key]);
322 }
323 }
324 }
325
326 $v3Fields = civicrm_api3($v3Entity, 'getfields', ['action' => $v3Action])['values'];
327
328 // Fix 'null'
329 foreach ($v3Params as $key => $val) {
330 if ($val === 'null') {
331 $v3Params[$key] = NULL;
332 }
333 }
334
335 if ($v4Entity == 'Setting') {
336 $indexBy = NULL;
337 $v4Params['domainId'] = \CRM_Utils_Array::value('domain_id', $v3Params);
338 if ($v3Action == 'getfields') {
339 if (!empty($v3Params['name'])) {
340 $v3Params['filters']['name'] = $v3Params['name'];
341 }
342 foreach (\CRM_Utils_Array::value('filters', $v3Params, []) as $filter => $val) {
343 $v4Params['where'][] = [$filter, '=', $val];
344 }
345 }
346 if ($v3Action == 'create') {
347 $v4Action = 'set';
348 }
349 if ($v3Action == 'revert') {
350 $v4Params['select'] = (array) $v3Params['name'];
351 }
352 if ($v3Action == 'getvalue') {
353 $options['return'] = [$v3Params['name'] => 1];
354 $v3Params = [];
355 }
356 \CRM_Utils_Array::remove($v3Params, 'domain_id', 'name');
357 }
358
359 \CRM_Utils_Array::remove($v3Params, 'options', 'debug', 'version', 'sort', 'offset', 'rowCount', 'check_permissions', 'sequential', 'filters', 'isCurrent');
360
361 // Work around ugly hack in v3 Domain api
362 if ($v4Entity == 'Domain') {
363 $v3Fields['version'] = ['name' => 'version', 'api.aliases' => ['domain_version']];
364 unset($v3Fields['domain_version']);
365 }
366
367 foreach ($v3Fields as $name => $field) {
368 // Resolve v3 aliases
369 foreach (\CRM_Utils_Array::value('api.aliases', $field, []) as $alias) {
370 if (isset($v3Params[$alias])) {
371 $v3Params[$field['name']] = $v3Params[$alias];
372 unset($v3Params[$alias]);
373 }
374 }
375 // Convert custom field names
376 if (strpos($name, 'custom_') === 0 && is_numeric($name[7])) {
377 // Strictly speaking, using titles instead of names is incorrect, but it works for
378 // unit tests where names and titles are identical and saves an extra db lookup.
379 $custom[$field['groupTitle']][$field['title']] = $name;
380 $v4FieldName = $field['groupTitle'] . '.' . $field['title'];
381 if (isset($v3Params[$name])) {
382 $v3Params[$v4FieldName] = $v3Params[$name];
383 unset($v3Params[$name]);
384 }
385 if (isset($options['return'][$name])) {
386 $options['return'][$v4FieldName] = 1;
387 unset($options['return'][$name]);
388 }
389 }
390 }
391
392 switch ($v3Action) {
393 case 'getcount':
394 $v4Params['select'] = ['row_count'];
395 // No break - keep processing as get
396 case 'getsingle':
397 case 'getvalue':
398 $v4Action = 'get';
399 // No break - keep processing as get
400 case 'get':
401 if ($options['return'] && $v3Action !== 'getcount') {
402 $v4Params['select'] = array_keys($options['return']);
403 }
404 if ($options['limit'] && $v4Entity != 'Setting') {
405 $v4Params['limit'] = $options['limit'];
406 }
407 if ($options['offset']) {
408 $v4Params['offset'] = $options['offset'];
409 }
410 if ($options['sort']) {
411 foreach (explode(',', $options['sort']) as $sort) {
412 list($sortField, $sortDir) = array_pad(explode(' ', trim($sort)), 2, 'ASC');
413 $v4Params['orderBy'][$sortField] = $sortDir;
414 }
415 }
416 break;
417
418 case 'replace':
419 if (empty($v3Params['values'])) {
420 $v4Action = 'delete';
421 }
422 else {
423 $v4Params['records'] = $v3Params['values'];
424 }
425 unset($v3Params['values']);
426 break;
427
428 case 'create':
429 case 'update':
430 if (!empty($v3Params['id'])) {
431 $v4Action = 'update';
432 $v4Params['where'][] = ['id', '=', $v3Params['id']];
433 }
434
435 $v4Params['values'] = $v3Params;
436 unset($v4Params['values']['id']);
437 break;
438
439 case 'delete':
440 if (!empty($v3Params['id'])) {
441 $v4Params['where'][] = ['id', '=', $v3Params['id']];
442 }
443 break;
444
445 case 'getoptions':
446 $indexBy = 0;
447 $v4Action = 'getFields';
448 $v4Params += [
449 'where' => [['name', '=', $v3Params['field']]],
450 'loadOptions' => TRUE,
451 ];
452 break;
453
454 case 'getfields':
455 $v4Action = 'getFields';
456 if (!empty($v3Params['action']) || !empty($v3Params['api_action'])) {
457 $v4Params['action'] = !empty($v3Params['action']) ? $v3Params['action'] : $v3Params['api_action'];
458 }
459 $indexBy = !$sequential ? 'name' : NULL;
460 break;
461 }
462
463 // Ensure this api4 entity/action exists
464 try {
465 $actionInfo = \civicrm_api4($v4Entity, 'getActions', ['checkPermissions' => FALSE, 'where' => [['name', '=', $v4Action]]]);
466 }
467 catch (NotImplementedException $e) {
468 // For now we'll mark the test incomplete if a v4 entity doesn't exit yet
469 $this->markTestIncomplete($e->getMessage());
470 }
471 if (!isset($actionInfo[0])) {
472 throw new \Exception("Api4 $v4Entity $v4Action does not exist.");
473 }
474
475 // Migrate special params like fix_address
476 foreach ($actionInfo[0]['params'] as $v4ParamName => $paramInfo) {
477 // camelCase in api4, lower_case in api3
478 $v3ParamName = strtolower(preg_replace('/(?=[A-Z])/', '_$0', $v4ParamName));
479 if (isset($v3Params[$v3ParamName])) {
480 $v4Params[$v4ParamName] = $v3Params[$v3ParamName];
481 unset($v3Params[$v3ParamName]);
482 if ($paramInfo['type'][0] == 'bool') {
483 $v4Params[$v4ParamName] = (bool) $v4Params[$v4ParamName];
484 }
485 }
486 }
487
488 // Build where clause for 'getcount', 'getsingle', 'getvalue', 'get' & 'replace'
489 if ($v4Action == 'get' || $v3Action == 'replace') {
490 foreach ($v3Params as $key => $val) {
491 $op = '=';
492 if (is_array($val) && count($val) == 1 && array_intersect_key($val, array_flip(\CRM_Core_DAO::acceptedSQLOperators()))) {
493 foreach ($val as $op => $newVal) {
494 $val = $newVal;
495 }
496 }
497 $v4Params['where'][] = [$key, $op, $val];
498 }
499 }
500
501 try {
502 $result = \civicrm_api4($v4Entity, $v4Action, $v4Params, $indexBy);
503 }
504 catch (\Exception $e) {
505 return $onlySuccess ? 0 : [
506 'is_error' => 1,
507 'error_message' => $e->getMessage(),
508 'version' => 4,
509 ];
510 }
511
512 if (($v3Action == 'getsingle' || $v3Action == 'getvalue') && count($result) != 1) {
513 return $onlySuccess ? 0 : [
514 'is_error' => 1,
515 'error_message' => "Expected one $v4Entity but found " . count($result),
516 'count' => count($result),
517 ];
518 }
519
520 if ($onlySuccess) {
521 return 1;
522 }
523
524 if ($v3Action == 'getcount') {
525 return $result->count();
526 }
527
528 if ($onlyId) {
529 return $result->first()['id'];
530 }
531
532 if ($v3Action == 'getvalue' && $v4Entity == 'Setting') {
533 return \CRM_Utils_Array::value('value', $result->first());
534 }
535
536 if ($v3Action == 'getvalue') {
537 return \CRM_Utils_Array::value(array_keys($options['return'])[0], $result->first());
538 }
539
540 // Mimic api3 behavior when using 'replace' action to delete all
541 if ($v3Action == 'replace' && $v4Action == 'delete') {
542 $result->exchangeArray([]);
543 }
544
545 if ($v3Action == 'getoptions') {
546 return [
547 'is_error' => 0,
548 'count' => $result['options'] ? count($result['options']) : 0,
549 'values' => $result['options'] ?: [],
550 'version' => 4,
551 ];
552 }
553
554 // Emulate the weird return format of api3 settings
555 if (($v3Action == 'get' || $v3Action == 'create') && $v4Entity == 'Setting') {
556 $settings = [];
557 foreach ($result as $item) {
558 $settings[$item['domain_id']][$item['name']] = $item['value'];
559 }
560 $result->exchangeArray($sequential ? array_values($settings) : $settings);
561 }
562
563 foreach ($result as $index => $row) {
564 // Run chains
565 foreach ($chains as $key => $params) {
566 $result[$index][$key] = $this->runApi4LegacyChain($key, $params, $v4Entity, $row, $sequential);
567 }
568 // Resolve custom field names
569 foreach ($custom as $group => $fields) {
570 if (isset($row[$group])) {
571 foreach ($fields as $field => $v3FieldName) {
572 if (isset($row[$group][$field])) {
573 $result[$index][$v3FieldName] = $row[$group][$field];
574 }
575 }
576 unset($result[$index][$group]);
577 }
578 }
579 }
580
581 if ($v3Action == 'getsingle') {
582 return $result->first();
583 }
584
585 return [
586 'is_error' => 0,
587 'version' => 4,
588 'count' => count($result),
589 'values' => (array) $result,
590 'id' => is_object($result) && count($result) == 1 ? \CRM_Utils_Array::value('id', $result->first()) : NULL,
591 ];
592 }
593
594 /**
595 * @param string $key
596 * @param mixed $params
597 * @param string $mainEntity
598 * @param array $result
599 * @param bool $sequential
600 * @return array
601 * @throws \API_Exception
602 */
603 protected function runApi4LegacyChain($key, $params, $mainEntity, $result, $sequential) {
604 // Handle an array of multiple calls using recursion
605 if (is_array($params) && isset($params[0]) && is_array($params[0])) {
606 $results = [];
607 foreach ($params as $chain) {
608 $results[] = $this->runApi4LegacyChain($key, $chain, $mainEntity, $result, $sequential);
609 }
610 return $results;
611 }
612
613 // Handle single api call
614 list(, $chainEntity, $chainAction) = explode('.', $key);
615 $lcChainEntity = \_civicrm_api_get_entity_name_from_camel($chainEntity);
616 $chainEntity = self::convertEntityNameToApi4($chainEntity);
617 $lcMainEntity = \_civicrm_api_get_entity_name_from_camel($mainEntity);
618 $params = is_array($params) ? $params : [];
619
620 // Api3 expects this to be inherited
621 $params += ['sequential' => $sequential];
622
623 // Replace $value.field_name
624 foreach ($params as $name => $param) {
625 if (is_string($param) && strpos($param, '$value.') === 0) {
626 $param = substr($param, 7);
627 $params[$name] = \CRM_Utils_Array::value($param, $result);
628 }
629 }
630
631 try {
632 $getFields = civicrm_api4($chainEntity, 'getFields', ['select' => ['name']], 'name');
633 }
634 catch (NotImplementedException $e) {
635 $this->markTestIncomplete($e->getMessage());
636 }
637
638 // Emulate the string-fu guesswork that api3 does
639 if ($chainEntity == $mainEntity && empty($params['id']) && !empty($result['id'])) {
640 $params['id'] = $result['id'];
641 }
642 elseif (empty($params['id']) && !empty($result[$lcChainEntity . '_id'])) {
643 $params['id'] = $result[$lcChainEntity . '_id'];
644 }
645 elseif (!empty($result['id']) && isset($getFields[$lcMainEntity . '_id']) && empty($params[$lcMainEntity . '_id'])) {
646 $params[$lcMainEntity . '_id'] = $result['id'];
647 }
648 return $this->runApi4Legacy($chainEntity, $chainAction, $params);
649 }
650
651 /**
652 * Fix the naming differences between api3 & api4 entities.
653 *
654 * @param string $legacyName
655 * @return string
656 */
657 public static function convertEntityNameToApi4($legacyName) {
658 $api4Name = \CRM_Utils_String::convertStringToCamel($legacyName);
659 $map = [
660 'Im' => 'IM',
661 'Acl' => 'ACL',
662 ];
663 return \CRM_Utils_Array::value($api4Name, $map, $api4Name);
664 }
665
30f5345c 666}