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