APIv3 - Improve array-based apis to support sorting and multiple operators
[civicrm-core.git] / tests / phpunit / api / v3 / UtilsTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 require_once 'CRM/Utils/DeprecatedUtils.php';
13
14 /**
15 * Test class for API utils
16 *
17 * @package CiviCRM
18 * @group headless
19 */
20 class api_v3_UtilsTest extends CiviUnitTestCase {
21 protected $_apiversion = 3;
22 public $DBResetRequired = FALSE;
23
24 public $_contactID = 1;
25
26 /**
27 * Sets up the fixture, for example, opens a network connection.
28 *
29 * This method is called before a test is executed.
30 */
31 protected function setUp() {
32 parent::setUp();
33 $this->useTransaction(TRUE);
34 }
35
36 public function testAddFormattedParam() {
37 $values = ['contact_type' => 'Individual'];
38 $params = ['something' => 1];
39 $result = _civicrm_api3_deprecated_add_formatted_param($values, $params);
40 $this->assertTrue($result);
41 }
42
43 public function testCheckPermissionReturn() {
44 $check = ['check_permissions' => TRUE];
45 $config = CRM_Core_Config::singleton();
46 $config->userPermissionClass->permissions = [];
47 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'empty permissions should not be enough');
48 $config->userPermissionClass->permissions = ['access CiviCRM'];
49 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'lacking permissions should not be enough');
50 $config->userPermissionClass->permissions = ['add contacts'];
51 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'lacking permissions should not be enough');
52
53 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts'];
54 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'exact permissions should be enough');
55
56 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts', 'import contacts'];
57 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'overfluous permissions should be enough');
58 }
59
60 public function testCheckPermissionThrow() {
61 $check = ['check_permissions' => TRUE];
62 $config = CRM_Core_Config::singleton();
63 try {
64 $config->userPermissionClass->permissions = ['access CiviCRM'];
65 $this->runPermissionCheck('contact', 'create', $check, TRUE);
66 }
67 catch (Exception $e) {
68 $message = $e->getMessage();
69 }
70 $this->assertEquals($message, 'API permission check failed for Contact/create call; insufficient permission: require access CiviCRM and add contacts', 'lacking permissions should throw an exception');
71
72 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts', 'import contacts'];
73 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'overfluous permissions should return true');
74 }
75
76 public function testCheckPermissionSkip() {
77 $config = CRM_Core_Config::singleton();
78 $config->userPermissionClass->permissions = ['access CiviCRM'];
79 $params = ['check_permissions' => TRUE];
80 $this->assertFalse($this->runPermissionCheck('contact', 'create', $params), 'lacking permissions should not be enough');
81 $params = ['check_permissions' => FALSE];
82 $this->assertTrue($this->runPermissionCheck('contact', 'create', $params), 'permission check should be skippable');
83 }
84
85 public function getCamelCaseFuncs() {
86 // There have been two slightly different functions for normalizing names;
87 // _civicrm_api_get_camel_name() and \Civi\API\Request::normalizeEntityName().
88 return [
89 // These are the typical cases - where the two have always agreed.
90 ['Foo', 'Foo'],
91 ['foo', 'Foo'],
92 ['FooBar', 'FooBar'],
93 ['foo_bar', 'FooBar'],
94 ['fooBar', 'FooBar'],
95 ['Im', 'Im'],
96 ['ACL', 'Acl'],
97 ['HTTP', 'HTTP'],
98
99 // These are some atypical cases - where the two have always agreed.
100 ['foo__bar', 'FooBar'],
101 ['Foo_Bar', 'FooBar'],
102 ['one_two_three', 'OneTwoThree'],
103 ['oneTwo_three', 'OneTwoThree'],
104 ['Got2B', 'Got2B'],
105 ['got2_BGood', 'Got2BGood'],
106
107 // These are some atypical cases - where they have traditionally disagreed.
108 // _civicrm_api_get_camel_name() has now changed to match normalizeEntityName()
109 // because the latter is more defensive.
110 ['Foo-Bar', 'FooBar'],
111 ['Foo+Bar', 'FooBar'],
112 ['Foo.Bar', 'FooBar'],
113 ['Foo/../Bar/', 'FooBar'],
114 ['./Foo', 'Foo'],
115 ];
116 }
117
118 /**
119 * @param string $inputValue
120 * The user-supplied/untrusted entity name.
121 * @param string $expectValue
122 * The normalized/UpperCamelCase entity name.
123 * @dataProvider getCamelCaseFuncs
124 */
125 public function testCamelName($inputValue, $expectValue) {
126 $actualValue = _civicrm_api_get_camel_name($inputValue);
127 $this->assertEquals($expectValue, $actualValue);
128 }
129
130 /**
131 * @param string $entity
132 * @param string $action
133 * @param array $params
134 * @param bool $throws
135 * Whether we should pass any exceptions for authorization failures.
136 *
137 * @throws API_Exception
138 * @throws Exception
139 * @return bool
140 * TRUE or FALSE depending on the outcome of the authorization check
141 */
142 public function runPermissionCheck($entity, $action, $params, $throws = FALSE) {
143 $params['version'] = 3;
144 $dispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
145 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
146 $kernel = new \Civi\API\Kernel($dispatcher);
147 $apiRequest = \Civi\API\Request::create($entity, $action, $params);
148 try {
149 $kernel->authorize(NULL, $apiRequest);
150 return TRUE;
151 }
152 catch (\API_Exception $e) {
153 $extra = $e->getExtraParams();
154 if (!$throws && $extra['error_code'] == API_Exception::UNAUTHORIZED) {
155 return FALSE;
156 }
157 else {
158 throw $e;
159 }
160 }
161 }
162
163 /**
164 * Test verify mandatory - includes DAO & passed as well as empty & NULL fields
165 */
166 public function testVerifyMandatory() {
167 _civicrm_api3_initialize(TRUE);
168 $params = [
169 'entity_table' => 'civicrm_contact',
170 'note' => '',
171 'contact_id' => $this->_contactID,
172 'modified_date' => '2011-01-31',
173 'subject' => NULL,
174 'version' => $this->_apiversion,
175 ];
176 try {
177 civicrm_api3_verify_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
178 }
179 catch (Exception $expected) {
180 $this->assertEquals('Mandatory key(s) missing from params array: note, subject', $expected->getMessage());
181 return;
182 }
183
184 $this->fail('An expected exception has not been raised.');
185 }
186
187 /**
188 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
189 */
190 public function testVerifyOneMandatory() {
191 _civicrm_api3_initialize(TRUE);
192 $params = [
193 'entity_table' => 'civicrm_contact',
194 'note' => '',
195 'contact_id' => $this->_contactID,
196 'modified_date' => '2011-01-31',
197 'subject' => NULL,
198 'version' => $this->_apiversion,
199 ];
200
201 try {
202 civicrm_api3_verify_one_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
203 }
204 catch (Exception $expected) {
205 $this->assertEquals('Mandatory key(s) missing from params array: one of (note, subject)', $expected->getMessage());
206 return;
207 }
208
209 $this->fail('An expected exception has not been raised.');
210 }
211
212 /**
213 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
214 */
215 public function testVerifyOneMandatoryOneSet() {
216 _civicrm_api3_initialize(TRUE);
217 $params = [
218 'version' => 3,
219 'entity_table' => 'civicrm_contact',
220 'note' => 'note',
221 'contact_id' => $this->_contactID,
222 'modified_date' => '2011-01-31',
223 'subject' => NULL,
224 ];
225
226 try {
227 civicrm_api3_verify_one_mandatory($params, NULL, ['note', 'subject']);
228 }
229 catch (Exception$expected) {
230 $this->fail('Exception raised when it shouldn\'t have been in line ' . __LINE__);
231 }
232 }
233
234 /**
235 * Test GET DAO function returns DAO.
236 */
237 public function testGetDAO() {
238 $params = [
239 'civicrm_api3_custom_group_get' => 'CRM_Core_DAO_CustomGroup',
240 'custom_group' => 'CRM_Core_DAO_CustomGroup',
241 'CustomGroup' => 'CRM_Core_DAO_CustomGroup',
242 'civicrm_api3_custom_field_get' => 'CRM_Core_DAO_CustomField',
243 'civicrm_api3_survey_get' => 'CRM_Campaign_DAO_Survey',
244 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_DAO_PledgePayment',
245 'civicrm_api3_website_get' => 'CRM_Core_DAO_Website',
246 'Membership' => 'CRM_Member_DAO_Membership',
247 ];
248 foreach ($params as $input => $expected) {
249 $result = _civicrm_api3_get_DAO($input);
250 $this->assertEquals($expected, $result);
251 }
252 }
253
254 /**
255 * Test GET BAO function returns BAO when it exists.
256 */
257 public function testGetBAO() {
258 $params = [
259 'civicrm_api3_website_get' => 'CRM_Core_BAO_Website',
260 'civicrm_api3_survey_get' => 'CRM_Campaign_BAO_Survey',
261 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_BAO_PledgePayment',
262 'Household' => 'CRM_Contact_BAO_Contact',
263 // Note this one DOES NOT have a BAO so we expect to fall back on returning the DAO
264 'mailing_group' => 'CRM_Mailing_DAO_MailingGroup',
265 // Make sure we get null back with nonexistant entities
266 'civicrm_this_does_not_exist' => NULL,
267 ];
268 foreach ($params as $input => $expected) {
269 $result = _civicrm_api3_get_BAO($input);
270 $this->assertEquals($expected, $result);
271 }
272 }
273
274 /**
275 * Test the validate function transforms dates.
276 *
277 * @throws \CiviCRM_API3_Exception
278 * @throws \Exception
279 */
280 public function test_civicrm_api3_validate_fields() {
281 $params = ['relationship_start_date' => '2010-12-20', 'relationship_end_date' => ''];
282 $fields = civicrm_api3('relationship', 'getfields', ['action' => 'get']);
283 _civicrm_api3_validate_fields('relationship', 'get', $params, $fields['values']);
284 $this->assertEquals('20101220000000', $params['relationship_start_date']);
285 $this->assertEquals('', $params['relationship_end_date']);
286 }
287
288 public function test_civicrm_api3_validate_fields_membership() {
289 $params = [
290 'start_date' => '2010-12-20',
291 'end_date' => '',
292 'membership_end_date' => '0',
293 'membership_join_date' => '2010-12-20',
294 'membership_start_date' => '2010-12-20',
295 ];
296 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
297 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
298 $this->assertEquals('2010-12-20', $params['start_date']);
299 $this->assertEquals('20101220000000', $params['membership_start_date']);
300 $this->assertEquals('', $params['end_date']);
301 $this->assertEquals('20101220000000', $params['membership_join_date'], 'join_date not set in line ' . __LINE__);
302 }
303
304 public function test_civicrm_api3_validate_fields_event() {
305
306 $params = [
307 'registration_start_date' => 20080601,
308 'registration_end_date' => '2008-10-15',
309 'start_date' => '2010-12-20',
310 'end_date' => '',
311 ];
312 $fields = civicrm_api3('Event', 'getfields', ['action' => 'create']);
313 _civicrm_api3_validate_fields('event', 'create', $params, $fields['values']);
314 $this->assertEquals('20101220000000', $params['start_date']);
315 $this->assertEquals('20081015000000', $params['registration_end_date']);
316 $this->assertEquals('', $params['end_date']);
317 $this->assertEquals('20080601000000', $params['registration_start_date']);
318 }
319
320 public function test_civicrm_api3_validate_fields_exception() {
321 $params = [
322 'membership_join_date' => 'abc',
323 ];
324 try {
325 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
326 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
327 }
328 catch (Exception$expected) {
329 $this->assertEquals('membership_join_date is not a valid date: abc', $expected->getMessage());
330 }
331 }
332
333 public function testGetFields() {
334 $result = $this->callAPISuccess('membership', 'getfields', []);
335 $this->assertArrayHasKey('values', $result);
336 $result = $this->callAPISuccess('relationship', 'getfields', []);
337 $this->assertArrayHasKey('values', $result);
338 $result = $this->callAPISuccess('event', 'getfields', []);
339 $this->assertArrayHasKey('values', $result);
340 }
341
342 public function testGetFields_AllOptions() {
343 $result = $this->callAPISuccess('contact', 'getfields', [
344 'options' => [
345 'get_options' => 'all',
346 ],
347 ]);
348 $this->assertEquals('Household', $result['values']['contact_type']['options']['Household']);
349 $this->assertEquals('HTML', $result['values']['preferred_mail_format']['options']['HTML']);
350 }
351
352 public function basicArrayCases() {
353 $records = [
354 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
355 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
356 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
357 ['snack_id' => 'd', 'fruit' => 'apple', 'cheese' => 'gouda'],
358 ['snack_id' => 'e', 'fruit' => 'apple', 'cheese' => 'provolone'],
359 ];
360
361 $cases[] = [
362 $records,
363 // params
364 ['version' => 3],
365 // expected results
366 ['a', 'b', 'c', 'd', 'e'],
367 ];
368
369 $cases[] = [
370 $records,
371 // params
372 ['version' => 3, 'fruit' => 'apple'],
373 // expected results
374 ['a', 'c', 'd', 'e'],
375 ];
376
377 $cases[] = [
378 $records,
379 ['version' => 3, 'cheese' => 'cheddar', 'options' => ['sort' => 'fruit desc']],
380 ['b', 'c'],
381 ];
382
383 $cases[] = [
384 $records,
385 ['version' => 3, 'cheese' => 'cheddar', 'options' => ['sort' => 'fruit']],
386 ['c', 'b'],
387 ];
388
389 $cases[] = [
390 $records,
391 ['version' => 3, 'cheese' => ['IS NOT NULL' => 1], 'options' => ['sort' => 'fruit, cheese']],
392 ['c', 'd', 'e', 'a', 'b'],
393 ];
394
395 $cases[] = [
396 $records,
397 ['version' => 3, 'id' => 'd'],
398 ['d'],
399 ];
400
401 $cases[] = [
402 $records,
403 ['version' => 3, 'fruit' => ['!=' => 'apple']],
404 ['b'],
405 ];
406
407 $cases[] = [
408 $records,
409 ['version' => 3, 'cheese' => ['LIKE' => '%o%']],
410 ['d', 'e'],
411 ];
412
413 $cases[] = [
414 $records,
415 ['version' => 3, 'cheese' => ['IN' => ['swiss', 'cheddar', 'gouda']]],
416 ['a', 'b', 'c', 'd'],
417 ];
418
419 return $cases;
420 }
421
422 /**
423 * Make a basic API (Widget.get) which allows getting data out of a simple in-memory
424 * list of records.
425 *
426 * @param $records
427 * The list of all records.
428 * @param $params
429 * The filter criteria
430 * @param array $resultIds
431 * The records which are expected to match.
432 * @dataProvider basicArrayCases
433 */
434 public function testBasicArrayGet($records, $params, $resultIds) {
435 $params['version'] = 3;
436
437 $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher());
438
439 $provider = new \Civi\API\Provider\AdhocProvider($params['version'], 'Widget');
440 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
441 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
442 });
443 $kernel->registerApiProvider($provider);
444
445 $r1 = $kernel->runSafe('Widget', 'get', $params);
446 $this->assertEquals(count($resultIds), $r1['count']);
447 $this->assertEquals($resultIds, array_keys($r1['values']));
448 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r1['values'])));
449 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r1['values'])));
450
451 $r2 = $kernel->runSafe('Widget', 'get', $params + ['sequential' => 1]);
452 $this->assertEquals(count($resultIds), $r2['count']);
453 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r2['values'])));
454 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r2['values'])));
455
456 $params['options']['offset'] = 1;
457 $params['options']['limit'] = 2;
458 $r3 = $kernel->runSafe('Widget', 'get', $params);
459 $slice = array_slice($resultIds, 1, 2);
460 $this->assertEquals(count($slice), $r3['count']);
461 $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('snack_id', $r3['values'])));
462 $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('id', $r3['values'])));
463 }
464
465 public function testBasicArrayGetReturn() {
466 $records = [
467 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
468 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
469 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
470 ];
471
472 $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher());
473 $provider = new \Civi\API\Provider\AdhocProvider(3, 'Widget');
474 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
475 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
476 });
477 $kernel->registerApiProvider($provider);
478
479 $r1 = $kernel->runSafe('Widget', 'get', [
480 'version' => 3,
481 'snack_id' => 'b',
482 'return' => 'fruit',
483 ]);
484 $this->assertAPISuccess($r1);
485 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape']], $r1['values']);
486
487 $r2 = $kernel->runSafe('Widget', 'get', [
488 'version' => 3,
489 'snack_id' => 'b',
490 'return' => ['fruit', 'cheese'],
491 ]);
492 $this->assertAPISuccess($r2);
493 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar']], $r2['values']);
494
495 $r3 = $kernel->runSafe('Widget', 'get', [
496 'version' => 3,
497 'cheese' => 'cheddar',
498 'return' => ['fruit'],
499 ]);
500 $this->assertAPISuccess($r3);
501 $this->assertEquals([
502 'b' => ['id' => 'b', 'fruit' => 'grape'],
503 'c' => ['id' => 'c', 'fruit' => 'apple'],
504 ], $r3['values']);
505 }
506
507 /**
508 * CRM-20892 Add Tests of new timestamp checking function
509 *
510 * @throws \CRM_Core_Exception
511 */
512 public function testTimeStampChecking() {
513 CRM_Core_DAO::executeQuery("INSERT INTO civicrm_mailing (id, modified_date) VALUES (25, '2016-06-30 12:52:52')");
514 $this->assertTrue(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
515 $this->callAPISuccess('Mailing', 'create', ['id' => 25, 'subject' => 'Test Subject']);
516 $this->assertFalse(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
517 $this->callAPISuccess('Mailing', 'delete', ['id' => 25]);
518 }
519
520 /**
521 * Test that the foreign key constraint test correctly interprets pseudoconstants.
522 *
523 * @throws \CRM_Core_Exception
524 * @throws \API_Exception
525 */
526 public function testKeyConstraintCheck() {
527 $fieldInfo = $this->callAPISuccess('Contribution', 'getfields', [])['values']['financial_type_id'];
528 _civicrm_api3_validate_constraint(1, 'financial_type_id', $fieldInfo, 'Contribution');
529 _civicrm_api3_validate_constraint('Donation', 'financial_type_id', $fieldInfo, 'Contribution');
530 try {
531 _civicrm_api3_validate_constraint('Blah', 'financial_type_id', $fieldInfo, 'Contribution');
532 }
533 catch (API_Exception $e) {
534 $this->assertEquals("'Blah' is not a valid option for field financial_type_id", $e->getMessage());
535 return;
536 }
537 $this->fail('Last function call should have thrown an exception');
538 }
539
540 }