-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathCiviUnitTestCase.php
3888 lines (3581 loc) · 119 KB
/
CiviUnitTestCase.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* File for the CiviUnitTestCase class
*
* (PHP 5)
*
* @copyright Copyright CiviCRM LLC (C) 2009
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html
* GNU Affero General Public License version 3
* @package CiviCRM
*
* This file is part of CiviCRM
*
* CiviCRM is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* CiviCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
use Civi\Api4\Contribution;
use Civi\Api4\CustomField;
use Civi\Api4\CustomGroup;
use Civi\Api4\LineItem;
use Civi\Api4\OptionGroup;
use Civi\Api4\RelationshipType;
use Civi\Payment\System;
use Civi\Api4\OptionValue;
use Civi\Test\Api3DocTrait;
use League\Csv\Reader;
/**
* Include class definitions
*/
require_once 'api/api.php';
define('API_LATEST_VERSION', 3);
/**
* Base class for CiviCRM unit tests
*
* This class supports two (mutually-exclusive) techniques for cleaning up test data. Subclasses
* may opt for one or neither:
*
* 1. quickCleanup() is a helper which truncates a series of tables. Call quickCleanup()
* as part of setUp() and/or tearDown(). quickCleanup() is thorough - but it can
* be cumbersome to use (b/c you must identify the tables to cleanup) and slow to execute.
* 2. useTransaction() executes the test inside a transaction. It's easier to use
* (because you don't need to identify specific tables), but it doesn't work for tests
* which manipulate schema or truncate data -- and could behave inconsistently
* for tests which specifically examine DB transactions.
*
* Common functions for unit tests
*
* @package CiviCRM
*/
class CiviUnitTestCase extends PHPUnit\Framework\TestCase {
use Api3DocTrait;
use \Civi\Test\GenericAssertionsTrait;
use \Civi\Test\DbTestTrait;
use \Civi\Test\ContactTestTrait;
use \Civi\Test\MailingTestTrait;
/**
* Database has been initialized.
*
* @var bool
*/
private static $dbInit = FALSE;
/**
* Database connection.
*
* @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
*/
protected $_dbconn;
/**
* The database name.
*
* @var string
*/
static protected $_dbName;
/**
* API version in use.
*
* @var int
*/
protected $_apiversion = 3;
/**
* Track tables we have modified during a test.
*
* @var array
*/
protected $_tablesToTruncate = [];
/**
* @var array
* Array of temporary directory names
*/
protected $tempDirs;
/**
* @var bool
* populateOnce allows to skip db resets in setUp
*
* WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
* BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
* "CHECK RUNS" ONLY!
*
* IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
*
* @see http://forum.civicrm.org/index.php/topic,18065.0.html
*/
public static $populateOnce = FALSE;
/**
* DBResetRequired allows skipping DB reset
* in specific test case. If you still need
* to reset single test (method) of such case, call
* $this->cleanDB() in the first line of this
* test (method).
* @var bool
*/
public $DBResetRequired = TRUE;
/**
* @var CRM_Core_Transaction|null
*/
private $tx = NULL;
/**
* Array of IDs created to support the test.
*
* e.g
* $this->ids = ['Contact' => ['descriptive_key' => $contactID], 'Group' => [$groupID]];
*
* @var array
*/
protected $ids = [];
/**
* Should financials be checked after the test but before tear down.
*
* Ideally all tests (or at least all that call any financial api calls ) should do this but there
* are some test data issues and some real bugs currently blocking.
*
* @var bool
*/
protected $isValidateFinancialsOnPostAssert = FALSE;
/**
* Should location types be checked to ensure primary addresses are correctly assigned after each test.
*
* @var bool
*/
protected $isLocationTypesOnPostAssert = TRUE;
/**
* Has the test class been verified as 'getsafe'.
*
* If a class is getsafe it means that where
* callApiSuccess is called 'return' is specified or 'return' =>'id'
* can be added by that function. This is part of getting away
* from open-ended get calls.
*
* Eventually we want to not be doing these in our test classes & start
* to work to not do them in our main code base. Note they mainly
* cause issues for activity.get and contact.get as these are where the
* too many joins limit is most likely to be hit.
*
* @var bool
*/
protected $isGetSafe = FALSE;
/**
* Class used for hooks during tests.
*
* This can be used to test hooks within tests. For example in the ACL_PermissionTrait:
*
* $this->hookClass->setHook('civicrm_aclWhereClause', [$this, 'aclWhereHookAllResults']);
*
* @var \CRM_Utils_Hook_UnitTests
*/
public $hookClass;
/**
* @var array
* Common values to be re-used multiple times within a class - usually to create the relevant entity
*/
protected $_params = [];
/**
* @var CRM_Extension_System
*/
protected $origExtensionSystem;
/**
* Array of IDs created during test setup routine.
*
* The cleanUpSetUpIds method can be used to clear these at the end of the test.
*
* @var array
*/
public $setupIDs = [];
/**
* Constructor.
*
* Because we are overriding the parent class constructor, we
* need to show the same arguments as exist in the constructor of
* PHPUnit_Framework_TestCase, since
* PHPUnit_Framework_TestSuite::createTest() creates a
* ReflectionClass of the Test class and checks the constructor
* of that class to decide how to set up the test.
*
* @param string $name
* @param array $data
* @param string $dataName
*/
public function __construct($name = NULL, array $data = [], $dataName = '') {
parent::__construct($name, $data, $dataName);
// we need full error reporting
error_reporting(E_ALL & ~E_NOTICE);
self::$_dbName = self::getDBName();
// also load the class loader
require_once 'CRM/Core/ClassLoader.php';
CRM_Core_ClassLoader::singleton()->register();
if (function_exists('_civix_phpunit_setUp')) {
// FIXME: loosen coupling
_civix_phpunit_setUp();
}
}
/**
* Override to run the test and assert its state.
*
* @return mixed
* @throws \Exception
* @throws \PHPUnit_Framework_IncompleteTest
* @throws \PHPUnit_Framework_SkippedTest
*/
protected function runTest() {
try {
return parent::runTest();
}
catch (PEAR_Exception $e) {
// PEAR_Exception has metadata in funny places, and PHPUnit won't log it nicely
throw new Exception(\CRM_Core_Error::formatTextException($e), $e->getCode());
}
}
/**
* @return bool
*/
public function requireDBReset() {
return $this->DBResetRequired;
}
/**
* @return string
*/
public static function getDBName() {
static $dbName = NULL;
if ($dbName === NULL) {
require_once "DB.php";
$dsn = CRM_Utils_SQL::autoSwitchDSN(CIVICRM_DSN);
$dsninfo = DB::parseDSN($dsn);
$dbName = $dsninfo['database'];
}
return $dbName;
}
/**
* Create database connection for this instance.
*
* Initialize the test database if it hasn't been initialized
*
*/
protected function getConnection() {
if (!self::$dbInit) {
$dbName = self::getDBName();
// install test database
echo PHP_EOL . "Installing {$dbName} database" . PHP_EOL;
static::_populateDB(FALSE, $this);
self::$dbInit = TRUE;
}
}
/**
* Required implementation of abstract method.
*/
protected function getDataSet() {
}
/**
* @param bool $perClass
* @param null $object
*
* @return bool
* TRUE if the populate logic runs; FALSE if it is skipped
*/
protected static function _populateDB($perClass = FALSE, &$object = NULL) {
if (CIVICRM_UF !== 'UnitTests') {
throw new \RuntimeException("_populateDB requires CIVICRM_UF=UnitTests");
}
if ($perClass || $object == NULL) {
$dbreset = TRUE;
}
else {
$dbreset = $object->requireDBReset();
}
if (self::$populateOnce || !$dbreset) {
return FALSE;
}
self::$populateOnce = NULL;
Civi\Test::data()->populate();
return TRUE;
}
public static function setUpBeforeClass(): void {
static::_populateDB(TRUE);
// also set this global hack
$GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = [];
}
/**
* Common setup functions for all unit tests.
*/
protected function setUp(): void {
$session = CRM_Core_Session::singleton();
$session->set('userID', NULL);
$this->_apiversion = 3;
// Use a temporary file for STDIN
$GLOBALS['stdin'] = tmpfile();
if ($GLOBALS['stdin'] === FALSE) {
echo "Couldn't open temporary file\n";
exit(1);
}
// Get and save a connection to the database
$this->_dbconn = $this->getConnection();
// reload database before each test
// $this->_populateDB();
// "initialize" CiviCRM to avoid problems when running single tests
// FIXME: look at it closer in second stage
$GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
$GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
// disable any left-over test extensions
CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
// reset all the caches
CRM_Utils_System::flushCache();
// initialize the object once db is loaded
\Civi::$statics = [];
// ugh, performance
$config = CRM_Core_Config::singleton(TRUE, TRUE);
// when running unit tests, use mockup user framework
$this->hookClass = CRM_Utils_Hook::singleton();
// Make sure the DB connection is setup properly
$config->userSystem->setMySQLTimeZone();
$env = new CRM_Utils_Check_Component_Env();
CRM_Utils_Check::singleton()->assertValid($env->checkMysqlTime());
// clear permissions stub to not check permissions
$config->userPermissionClass->permissions = NULL;
//flush component settings
CRM_Core_Component::getEnabledComponents(TRUE);
$_REQUEST = $_GET = $_POST = [];
error_reporting(E_ALL);
$this->renameLabels();
$this->_sethtmlGlobals();
$this->ensureMySQLMode(['IGNORE_SPACE', 'ERROR_FOR_DIVISION_BY_ZERO', 'STRICT_TRANS_TABLES']);
}
/**
* Read everything from the datasets directory and insert into the db.
*/
public function loadAllFixtures(): void {
$fixturesDir = __DIR__ . '/../../fixtures';
CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
$jsonFiles = glob($fixturesDir . '/*.json');
foreach ($jsonFiles as $jsonFixture) {
$json = json_decode(file_get_contents($jsonFixture));
foreach ($json as $tableName => $vars) {
if ($tableName === 'civicrm_contact') {
CRM_Core_DAO::executeQuery('DELETE c FROM civicrm_contact c LEFT JOIN civicrm_domain d ON d.contact_id = c.id WHERE d.id IS NULL');
}
else {
CRM_Core_DAO::executeQuery("TRUNCATE $tableName");
}
foreach ($vars as $entity) {
$keys = $values = [];
foreach ($entity as $key => $value) {
$keys[] = $key;
$values[] = is_numeric($value) ? $value : "'{$value}'";
}
CRM_Core_DAO::executeQuery("
INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
);
}
}
}
CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
}
/**
* Load the data that used to be handled by the discontinued dbunit class.
*
* This could do with further tidy up - the initial priority is simply to get rid of
* the dbunity package which is no longer supported.
*
* @param string $fileName
*/
protected function loadXMLDataSet($fileName) {
CRM_Core_DAO::executeQuery('SET FOREIGN_KEY_CHECKS = 0');
$xml = json_decode(json_encode(simplexml_load_file($fileName)), TRUE);
foreach ($xml as $tableName => $element) {
if (!empty($element)) {
foreach ($element as $row) {
$keys = $values = [];
if (isset($row['@attributes'])) {
foreach ($row['@attributes'] as $key => $value) {
$keys[] = $key;
$values[] = is_numeric($value) ? $value : "'{$value}'";
}
}
elseif (!empty($row)) {
// cos we copied it & it is inconsistent....
foreach ($row as $key => $value) {
$keys[] = $key;
$values[] = is_numeric($value) ? $value : "'{$value}'";
}
}
if (!empty($values)) {
CRM_Core_DAO::executeQuery("
INSERT INTO $tableName (" . implode(',', $keys) . ') VALUES(' . implode(',', $values) . ')'
);
}
}
}
}
CRM_Core_DAO::executeQuery('SET FOREIGN_KEY_CHECKS = 1');
}
/**
* Create default domain contacts for the two domains added during test class.
* database population.
*
* @throws \API_Exception
*/
public function createDomainContacts(): void {
$this->organizationCreate(['api.Email.create' => ['email' => '[email protected]']]);
$this->organizationCreate([
'organization_name' => 'Second Domain',
'api.Email.create' => ['email' => '[email protected]'],
'api.Address.create' => [
'street_address' => '15 Main St',
'location_type_id' => 1,
'city' => 'Collinsville',
'country_id' => 1228,
'state_province_id' => 1003,
'postal_code' => 6022,
],
]);
OptionValue::replace(FALSE)->addWhere(
'option_group_id:name', '=', 'from_email_address'
)->setDefaults([
'is_default' => 1,
'name' => '"FIXME" <[email protected]>',
'label' => '"FIXME" <[email protected]>',
])->setRecords([['domain_id' => 1], ['domain_id' => 2]])->execute();
}
/**
* Common teardown functions for all unit tests.
*
* @throws \CiviCRM_API3_Exception
* @throws \CRM_Core_Exception
* @throws \API_Exception
*/
protected function tearDown(): void {
$this->_apiversion = 3;
$this->resetLabels();
error_reporting(E_ALL & ~E_NOTICE);
CRM_Utils_Hook::singleton()->reset();
if ($this->hookClass) {
$this->hookClass->reset();
}
CRM_Core_Session::singleton()->reset(1);
if ($this->tx) {
$this->tx->rollback()->commit();
$this->tx = NULL;
CRM_Core_Transaction::forceRollbackIfEnabled();
\Civi\Core\Transaction\Manager::singleton(TRUE);
}
else {
CRM_Core_Transaction::forceRollbackIfEnabled();
\Civi\Core\Transaction\Manager::singleton(TRUE);
$tablesToTruncate = ['civicrm_contact', 'civicrm_uf_match', 'civicrm_email', 'civicrm_address'];
$this->quickCleanup($tablesToTruncate);
$this->createDomainContacts();
}
$this->cleanTempDirs();
$this->unsetExtensionSystem();
$this->assertEquals([], CRM_Core_DAO::$_nullArray);
$this->assertEquals(NULL, CRM_Core_DAO::$_nullObject);
// Ensure the destruct runs by unsetting it. Also, unsetting
// classes frees memory as they are not otherwise unset until the
// very end.
unset($this->mut);
}
/**
* CHeck that all tests that have created payments have created them with the right financial entities.
*
* @throws \API_Exception
* @throws \CRM_Core_Exception
*/
protected function assertPostConditions(): void {
// Reset to version 3 as not all (e.g payments) work on v4
$this->_apiversion = 3;
if ($this->isLocationTypesOnPostAssert) {
$this->assertLocationValidity();
}
$this->assertCount(1, OptionGroup::get(FALSE)
->addWhere('name', '=', 'from_email_address')
->execute());
if (!$this->isValidateFinancialsOnPostAssert) {
return;
}
$this->validateAllPayments();
$this->validateAllContributions();
}
/**
* Create a batch of external API calls which can
* be executed concurrently.
*
* ```
* $calls = $this->createExternalAPI()
* ->addCall('Contact', 'get', ...)
* ->addCall('Contact', 'get', ...)
* ...
* ->run()
* ->getResults();
* ```
*
* @return \Civi\API\ExternalBatch
* @throws PHPUnit_Framework_SkippedTestError
*/
public function createExternalAPI() {
global $civicrm_root;
$defaultParams = [
'version' => $this->_apiversion,
'debug' => 1,
];
$calls = new \Civi\API\ExternalBatch($defaultParams);
if (!$calls->isSupported()) {
$this->markTestSkipped('The test relies on Civi\API\ExternalBatch. This is unsupported in the local environment.');
}
return $calls;
}
/**
* Create required data based on $this->entity & $this->params
* This is just a way to set up the test data for delete & get functions
* so the distinction between set
* up & tested functions is clearer
*
* @return array
* api Result
*/
public function createTestEntity() {
return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
}
/**
* @param int $contactTypeId
*
* @throws Exception
*/
public function contactTypeDelete($contactTypeId) {
$result = CRM_Contact_BAO_ContactType::del($contactTypeId);
if (!$result) {
throw new Exception('Could not delete contact type');
}
}
/**
* @param array $params
*
* @return int
*/
public function membershipTypeCreate($params = []) {
CRM_Member_PseudoConstant::flush('membershipType');
CRM_Core_Config::clearDBCache();
$this->setupIDs['contact'] = $memberOfOrganization = $this->organizationCreate();
$params = array_merge([
'name' => 'General',
'duration_unit' => 'year',
'duration_interval' => 1,
'period_type' => 'rolling',
'member_of_contact_id' => $memberOfOrganization,
'domain_id' => 1,
'financial_type_id' => 2,
'is_active' => 1,
'sequential' => 1,
'visibility' => 'Public',
], $params);
$result = $this->callAPISuccess('MembershipType', 'Create', $params);
CRM_Member_PseudoConstant::flush('membershipType');
CRM_Utils_Cache::singleton()->flush();
return (int) $result['id'];
}
/**
* Create membership.
*
* @param array $params
*
* @return int
* @throws \CRM_Core_Exception
*/
public function contactMembershipCreate($params) {
$params = array_merge([
'join_date' => '2007-01-21',
'start_date' => '2007-01-21',
'end_date' => '2007-12-21',
'source' => 'Payment',
'membership_type_id' => 'General',
], $params);
if (!is_numeric($params['membership_type_id'])) {
$membershipTypes = $this->callAPISuccess('Membership', 'getoptions', ['action' => 'create', 'field' => 'membership_type_id']);
if (!in_array($params['membership_type_id'], $membershipTypes['values'], TRUE)) {
$this->membershipTypeCreate(['name' => $params['membership_type_id']]);
}
}
$result = $this->callAPISuccess('Membership', 'create', $params);
return $result['id'];
}
/**
* Delete Membership Type.
*
* @param array $params
*/
public function membershipTypeDelete($params) {
$this->callAPISuccess('MembershipType', 'Delete', $params);
}
/**
* @param int $membershipID
*/
public function membershipDelete($membershipID) {
$deleteParams = ['id' => $membershipID];
$result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
}
/**
* @param string $name
*
* @return mixed
*
* @throws \CRM_Core_Exception
*/
public function membershipStatusCreate($name = 'test member status') {
$params['name'] = $name;
$params['start_event'] = 'start_date';
$params['end_event'] = 'end_date';
$params['is_current_member'] = 1;
$params['is_active'] = 1;
$result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
CRM_Member_PseudoConstant::flush('membershipStatus');
return (int) $result['id'];
}
/**
* Delete the given membership status, deleting any memberships of the status first.
*
* @param int $membershipStatusID
*
* @throws \CRM_Core_Exception
*/
public function membershipStatusDelete(int $membershipStatusID) {
$this->callAPISuccess('Membership', 'get', ['status_id' => $membershipStatusID, 'api.Membership.delete' => 1]);
$this->callAPISuccess('MembershipStatus', 'Delete', ['id' => $membershipStatusID]);
}
public function membershipRenewalDate($durationUnit, $membershipEndDate) {
// We only have an end_date if frequency units match, otherwise membership won't be autorenewed and dates won't be calculated.
$renewedMembershipEndDate = new DateTime($membershipEndDate);
switch ($durationUnit) {
case 'year':
$renewedMembershipEndDate->add(new DateInterval('P1Y'));
break;
case 'month':
// We have to add 1 day first in case it's the end of the month, then subtract afterwards
// eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
$renewedMembershipEndDate->add(new DateInterval('P1D'));
$renewedMembershipEndDate->add(new DateInterval('P1M'));
$renewedMembershipEndDate->sub(new DateInterval('P1D'));
break;
}
return $renewedMembershipEndDate->format('Y-m-d');
}
/**
* Create a relationship type.
*
* @param array $params
*
* @return int
*
* @throws \CRM_Core_Exception
*/
public function relationshipTypeCreate($params = []) {
$params = array_merge([
'name_a_b' => 'Relation 1 for relationship type create',
'name_b_a' => 'Relation 2 for relationship type create',
'contact_type_a' => 'Individual',
'contact_type_b' => 'Organization',
'is_reserved' => 1,
'is_active' => 1,
], $params);
$result = $this->callAPISuccess('relationship_type', 'create', $params);
CRM_Core_PseudoConstant::flush('relationshipType');
return $result['id'];
}
/**
* Delete Relatinship Type.
*
* @param int $relationshipTypeID
*/
public function relationshipTypeDelete($relationshipTypeID) {
$params['id'] = $relationshipTypeID;
$check = $this->callAPISuccess('relationship_type', 'get', $params);
if (!empty($check['count'])) {
$this->callAPISuccess('relationship_type', 'delete', $params);
}
}
/**
* @param array $params
*
* @return mixed
* @throws \CRM_Core_Exception
*/
public function paymentProcessorTypeCreate($params = []) {
$params = array_merge([
'name' => 'API_Test_PP',
'title' => 'API Test Payment Processor',
'class_name' => 'CRM_Core_Payment_APITest',
'billing_mode' => 'form',
'is_recur' => 0,
'is_reserved' => 1,
'is_active' => 1,
], $params);
$result = $this->callAPISuccess('PaymentProcessorType', 'create', $params);
CRM_Core_PseudoConstant::flush('paymentProcessorType');
return $result['id'];
}
/**
* Create test Authorize.net instance.
*
* @param array $params
*
* @return mixed
* @throws \CRM_Core_Exception
*/
public function paymentProcessorAuthorizeNetCreate($params = []) {
$params = array_merge([
'name' => 'Authorize',
'domain_id' => CRM_Core_Config::domainID(),
'payment_processor_type_id' => 'AuthNet',
'title' => 'AuthNet',
'is_active' => 1,
'is_default' => 0,
'is_test' => 1,
'is_recur' => 1,
'user_name' => '4y5BfuW7jm',
'password' => '4cAmW927n8uLf5J8',
'url_site' => 'https://test.authorize.net/gateway/transact.dll',
'url_recur' => 'https://apitest.authorize.net/xml/v1/request.api',
'class_name' => 'Payment_AuthorizeNet',
'billing_mode' => 1,
], $params);
$result = $this->callAPISuccess('PaymentProcessor', 'create', $params);
return (int) $result['id'];
}
/**
* Create Participant.
*
* @param array $params
* Array of contact id and event id values.
*
* @return int
* $id of participant created
*/
public function participantCreate($params = []) {
if (empty($params['contact_id'])) {
$params['contact_id'] = $this->individualCreate();
}
if (empty($params['event_id'])) {
$event = $this->eventCreate();
$params['event_id'] = $event['id'];
}
$defaults = [
'status_id' => 2,
'role_id' => 1,
'register_date' => 20070219,
'source' => 'Wimbeldon',
'event_level' => 'Payment',
'debug' => 1,
];
$params = array_merge($defaults, $params);
$result = $this->callAPISuccess('Participant', 'create', $params);
return $result['id'];
}
/**
* Create Payment Processor.
*
* @return int
* Id Payment Processor
*/
public function processorCreate($params = []) {
$processorParams = [
'domain_id' => 1,
'name' => 'Dummy',
'payment_processor_type_id' => 'Dummy',
'financial_account_id' => 12,
'is_test' => TRUE,
'is_active' => 1,
'user_name' => '',
'url_site' => 'http://dummy.com',
'url_recur' => 'http://dummy.com',
'billing_mode' => 1,
'sequential' => 1,
'payment_instrument_id' => 'Debit Card',
];
$processorParams = array_merge($processorParams, $params);
$processor = $this->callAPISuccess('PaymentProcessor', 'create', $processorParams);
return $processor['id'];
}
/**
* Create Payment Processor.
*
* @param array $processorParams
*
* @return \CRM_Core_Payment_Dummy
* Instance of Dummy Payment Processor
*
* @throws \CiviCRM_API3_Exception
*/
public function dummyProcessorCreate($processorParams = []) {
$paymentProcessorID = $this->processorCreate($processorParams);
// For the tests we don't need a live processor, but as core ALWAYS creates a processor in live mode and one in test mode we do need to create both
// Otherwise we are testing a scenario that only exists in tests (and some tests fail because the live processor has not been defined).
$processorParams['is_test'] = FALSE;
$this->processorCreate($processorParams);
return System::singleton()->getById($paymentProcessorID);
}
/**
* Create contribution page.
*
* @param array $params
*
* @return array
* Array of contribution page
*/
public function contributionPageCreate($params = []) {
$this->_pageParams = array_merge([
'title' => 'Test Contribution Page',
'financial_type_id' => 1,
'currency' => 'USD',
'financial_account_id' => 1,
'is_active' => 1,
'is_allow_other_amount' => 1,
'min_amount' => 10,
'max_amount' => 1000,
], $params);
return $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
}
/**
* Create a sample batch.
*/
public function batchCreate() {
$params = $this->_params;
$params['name'] = $params['title'] = 'Batch_433397';
$params['status_id'] = 1;
$result = $this->callAPISuccess('batch', 'create', $params);
return $result['id'];
}
/**
* Create Tag.
*
* @param array $params
*
* @return array
* result of created tag
*/
public function tagCreate($params = []) {
$defaults = [
'name' => 'New Tag3',
'description' => 'This is description for Our New Tag ',
'domain_id' => '1',
];
$params = array_merge($defaults, $params);
$result = $this->callAPISuccess('Tag', 'create', $params);
return $result['values'][$result['id']];
}
/**
* Delete Tag.
*
* @param int $tagId
* Id of the tag to be deleted.
*
* @return int
*/
public function tagDelete($tagId) {
require_once 'api/api.php';
$params = [
'tag_id' => $tagId,
];
$result = $this->callAPISuccess('Tag', 'delete', $params);
return $result['id'];
}
/**
* Add entity(s) to the tag
*
* @param array $params