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