-
Notifications
You must be signed in to change notification settings - Fork 173
/
Candidate.class.inc
1239 lines (1111 loc) · 38.6 KB
/
Candidate.class.inc
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 declare(strict_types=1);
/**
* This file contains a class which is a wrapper around the concept
* of a candidate in Loris.
*
* @license GPLv3 <http://www.gnu.org/licenses/gpl-3.0.en.html>
*/
use LORIS\StudyEntities\Candidate\CandID;
use LORIS\StudyEntities\Candidate\EntityType;
use LORIS\StudyEntities\Candidate\Sex;
/* Define constants used by the file */
// error codes
define('CANDIDATE_INVALID', 1);
define('PSCID_NOT_SPECIFIED', 2);
define('PSCID_NOT_UNIQUE', 3);
define('PSCID_INVALID_STRUCTURE', 4);
define('EDC_NOT_SPECIFIED', 5);
define('DOB_NOT_SPECIFIED', 6);
define('DOB_INVALID', 7);
define('EDC_INVALID', 8);
/**
* Wrapper around a candidate in Loris. Mostly, it gets information
* from the candidate table, but this class is abstract enough that
* it could get information from other places too such as parameter_candidate
* if relevant.
*
* @category Main
* @package Loris
* @author Alex Zijdenbos <zijdenbos@example.com>
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
* @link https://www.github.com/aces/Loris-Trunk/
*/
class Candidate implements \LORIS\StudyEntities\AccessibleResource,
\LORIS\StudyEntities\SiteHaver
{
var $candidateInfo;
protected $data;
/**
* Construct a new Candidate object optionally populated by
* the given DTO.
*
* @param ?CandidateData $data a Candidate DTO object to bypass
* the singleton constructor.
*/
public function __construct(?CandidateData $data=null)
{
$this->data = $data;
}
/**
* This returns a single Candidate object for the given
* candID, and will only ever instantiate one object in
* the event that it's called multiple times.
*
* @param CandID $candID A 6 digit Loris CandID that matches
* a candidate in the candidate table
*
* @return Candidate the Candidate object
* @static
*/
static public function &singleton(CandID $candID)
{
$candidateList =& $GLOBALS['__candidateObjects'];
if (!isset($candidateList[strval($candID)])) {
$candidateList[strval($candID)] = new Candidate();
$candidateList[strval($candID)]->select($candID);
}
return $candidateList[strval($candID)];
}
/**
* This does the work of selecting the candidate and related
* information from the database and populating it into the
* Candidate object. Used by singleton method.
*
* @param CandID $candID The 6 digit Loris CandID
*
* @return void As a side-effect loads candidate into current
* object
* @throws DatabaseException | LorisException
*/
public function select(CandID $candID): void
{
$factory = NDB_Factory::singleton();
$config = $factory->config();
$CandArray = ['Candidate' => (string) $candID];
// make a local reference to the Database object
$db = $factory->database();
// get candidate data from database
$query = "SELECT c.RegistrationCenterID, c.CandID, c.PSCID, c.DoB,
c.EDC, c.Sex, c.Entity_type,
p.Name AS PSC, c.Ethnicity,
c.Active, u1.Real_name as RegisteredBy,
c.UserID, c.RegistrationProjectID
FROM candidate as c
LEFT JOIN psc as p ON (p.CenterID=c.RegistrationCenterID)
LEFT JOIN users as u1 ON (u1.UserID = c.RegisteredBy)
WHERE c.CandID=:Candidate AND c.Active = 'Y'";
$row = $db->pselectRow($query, $CandArray);
if (!is_array($row) || sizeof($row) == 0) {
throw new \LorisException(
"Could not select Candidate data from the database (DCCID: $candID)",
CANDIDATE_INVALID
);
}
// We need to refer to these when instantiating the CandidateData
// object after Timepoints have been selected, but by then $row
// will have been overwritten, so put them in other variables.
// Initialize them to null, they should get set in the foreach loop.
$registrationProjectID = null;
$registrationCenterID = null;
// store user data in object property
foreach ($row as $key=>$value) {
switch ($key) {
case 'Sex':
$this->candidateInfo[$key] = empty($value) ? null : new Sex($value);
break;
case 'Entity_type':
$this->candidateInfo[$key] = new EntityType($value);
break;
case 'RegistrationProjectID':
$registrationProjectID = new \ProjectID($value);
$this->candidateInfo[$key] = $registrationProjectID;
break;
case 'RegistrationCenterID':
$registrationCenterID = new \CenterID($value);
$this->candidateInfo[$key] = $registrationCenterID;
break;
default:
$this->candidateInfo[$key] = $value;
}
}
$headerSetting = $config->getSetting('HeaderTable');
if (!empty($headerSetting)) {
$params = [];
$parameterCandSettings = $headerSetting['parameter_candidate'];
if (!is_array($parameterCandSettings)) {
$parameterCandSettings = [$parameterCandSettings];
}
foreach ($parameterCandSettings as $parameter_type) {
$row = $db->pselectRow(
"SELECT Value, pt.Description
FROM candidate c
JOIN parameter_candidate pc ON (pc.CandID=c.CandID)
LEFT JOIN parameter_type pt ON
(pc.ParameterTypeID=pt.ParameterTypeID)
WHERE c.CandID=:Candidate AND pt.Name=:PTName",
[
'Candidate' => $candID,
'PTName' => $parameter_type,
]
);
// Sanitize values coming from the parameter_candidate table
// before injecting them into the HTML table.
if (!empty($row['Value'])) {
$params[$row['Description']] = htmlentities(
$row['Value'],
ENT_QUOTES,
'UTF-8'
);
}
}
$this->candidateInfo['DisplayParameters'] = $params;
}
// check that PSCID matches CandID when entered into the boxes
// on the candidate_list form (and is therefore trying to open
// the timepoint_list page, which is why the if statement checks
// for timepoint_list instead of candidate_list)
//
// Since other pages (ie. the filter in the conflicts_resolve page)
// might include an element named PSCID, we also need to check that
// the test_name matches before throwing the error.
if (isset($_REQUEST['PSCID'])
&& (isset($_REQUEST['test_name'])
&& $_REQUEST['test_name']=='timepoint_list')
) {
if (strtolower(
trim($_REQUEST['PSCID'])
) != strtolower($this->getPSCID())
) {
throw new \LorisException("IDs do not match");
}
}
// get Time Point SessionIDs for the $candID
$query = "SELECT s.ID, s.ProjectID, s.CenterID FROM session as s
WHERE s.CandID=:Candidate AND s.Active='Y'
ORDER BY ID";
$row = $db->pselect($query, $CandArray);
// store user data in object property
$timepoints = [];
foreach ($row as $value) {
$timepoints[] = new TimePoint(
new TimePointData(
new SessionID(strval($value["ID"])),
new ProjectID(strval($value["ProjectID"])),
new CenterID(strval($value["CenterID"])),
)
);
}
$this->data = new CandidateData(
$candID,
$registrationProjectID,
$registrationCenterID,
$timepoints,
);
$this->candidateInfo['ProjectTitle'] = $this->getProjectTitle();
}
/**
* Creates a new candidate, assigning CandID and PSCID.
*
* FIXME Ideally the signature of this function should be changed so that
* $useEDC is the second-to-last parameter. This would add some clarity as
* it is an optional parameter based on configuration
* settings. However, this will not be backward compatiable.
*
* @param CenterID $centerID centerID of the site to which the
* candidate will belong
* @param string|null $dateOfBirth date of birth written as YYYY-MM-DD
* @param string|null $edc estimated date of confinement
* written as YYYY-MM-DD. Value
* should be null unless the
* useEDC setting is configured
* to be true.
* @param Sex $sex An instance of the Sex class.
* @param string|null $PSCID PSCID specified by the user,
* if available
* @param ?ProjectID $registrationProjectID The project ID, if available
*
* @return CandID $candID candidate id of the new candidate
* @throws Exception
* @static
*/
static public function createNew(
CenterID $centerID,
?string $dateOfBirth,
?string $edc,
Sex $sex,
?string $PSCID = null,
ProjectID $registrationProjectID = null
): CandID {
$factory = NDB_Factory::singleton();
$db = $factory->database();
$site = \Site::singleton($centerID);
$project = \Project::getProjectFromID($registrationProjectID);
$user = \User::singleton($_SESSION['State']->getUsername());
// figure out how to generate PSCID
$config = $factory->config();
$PSCIDSettings = $config->getSetting('PSCID');
$useEDC = $config->getSetting('useEDC');
// Get expected format from config
$dobFormat = $config->getSetting('dobFormat');
$dobFormat = '!' . implode("-", str_split($dobFormat, 1));
if (($useEDC === '1' || $useEDC === 'true')) {
if (empty($edc)) {
throw new \LorisException(
"EDC must be specified",
EDC_NOT_SPECIFIED
);
} else {
// Check valid format
$edcDate = DateTime::createFromFormat($dobFormat, $edc);
if ($edcDate === false) {
throw new InvalidArgumentException(
"EDC is invalid (expected format: YYYY-MM-DD)",
EDC_INVALID
);
}
// Add day as mid of the month if Y-m dob format
// This allows insert into sql candidate table
if ($dobFormat === '!Y-m') {
$edc .= '-15';
}
}
}
if (empty($dateOfBirth)) {
// DoB not required if useEDC is on
if (!($useEDC === '1' || $useEDC === 'true')) {
throw new InvalidArgumentException(
"Date of Birth must be specified",
DOB_NOT_SPECIFIED
);
} else {
$dateOfBirth = null;
}
} else {
$dob = DateTime::createFromFormat($dobFormat, $dateOfBirth);
if ($dob === false) {
throw new InvalidArgumentException(
"Date of Birth is invalid (expected format: YYYY-MM-DD)",
DOB_INVALID
);
}
// Add day as mid of the month if Y-m dob format
// This allows insert into sql candidate table
if ($dobFormat === '!Y-m') {
$dateOfBirth .= '-15';
}
}
if ($PSCIDSettings['generation'] == 'user') {
// check pscid is specified
if (empty($PSCID)) {
throw new Exception(
"PSCID must be specified",
PSCID_NOT_SPECIFIED
);
}
// check pscid uniqueness
$existing = $db->pselectOne(
'SELECT
COUNT(*)
FROM candidate
WHERE PSCID = :v_pscid
GROUP BY
PSCID
',
['v_pscid' => $PSCID]
);
if ($existing > 0) {
throw new \ConflictException(
"PSCID must be unique",
PSCID_NOT_UNIQUE
);
}
// check pscid structure
if (!Candidate::validatePSCID(
$PSCID,
$site->getSiteAlias(),
$project->getAlias()
)
) {
throw new LorisException(
"PSCID has an invalid structure",
PSCID_INVALID_STRUCTURE
);
}
} else {
$PSCID = (new \PSCIDGenerator(
$site->getSiteAlias(),
$project->getAlias()
)
)->generate();
}
// Insert the new candidate into the database if everything is fine.
$setArray = [
'RegistrationCenterID' => $centerID,
'PSCID' => $PSCID,
'DoB' => $dateOfBirth,
'EDC' => $edc,
'Sex' => $sex,
'RegistrationProjectID' => $registrationProjectID,
'Date_active' => date('Y-m-d'),
'Date_registered' => date('Y-m-d'),
'Entity_type' => 'Human',
'RegisteredBy' => $user->getUsername(),
'UserID' => $user->getUsername(),
];
if ($config->getSetting('useExternalID') === 'true') {
$externalID = (new \ExternalIDGenerator(
$site->getSiteAlias(),
$project->getAlias()
))->generate();
$setArray['ExternalID'] = $externalID;
}
// Generate a new CandID and insert it into the database.
$generator = new \CandIDGenerator();
// declare the variable to avoid static analysis warnings
$attemptcount = 0;
$db = \NDB_Factory::singleton()->database();
do {
// Reset on each iteration
$invalidID = false;
// Generate candid and insert into setArray
$candID = $generator->generate();
$setArray['CandID'] = (string) $candID;
try {
$db->insert('candidate', $setArray);
} catch (\DatabaseException | \DomainException $e) {
// Occurs in the case of a race condition where another CandID
// with the same value has been inserted into the DB before this
// one.
$invalidID = true;
$attemptcount++;
if ($attemptcount > 2) {
throw $e;
}
}
} while ($invalidID);
// Return the new CandID
return $candID;
}
/**
* Checks if candidate exist given a candidate ID and PSCID
* Used to check that PSCID matches CandID when entered into the boxes
* on the candidate_list form
*
* @param CandID $candID 6 digit Loris CandID
* @param string $PSCID project study center ID
*
* @return bool TRUE if candidate is found (in candidate table), FALSE otherwise
* @throws DatabaseException
*/
static function candidateExists(CandID $candID, string $PSCID): bool
{
// make a local reference to the Database object
$factory = NDB_Factory::singleton();
$db = $factory->database();
$candidateIDs = [
':candidate_id' => $candID,
':pscid' => $PSCID,
];
// get candidate data from database
$query = "SELECT CandID
FROM candidate
WHERE CandID = :candidate_id AND PSCID = :pscid
AND Active = 'Y'";
$row = $db->pselectRow($query, $candidateIDs);
return $row !== null;
}
/**
* Get a list of timepoints that this Candidate has registered
*
* @return array Non-associative array of SessionIDs 1st Time Point
* indexed to 0
*/
function getListOfTimePoints(): array
{
return array_map(
function ($timepoint) {
return intval(
strval($timepoint->getSessionID())
);
},
$this->data->timepoints,
);
}
/**
* Returns the sessionID for this Candidate's nth visit
*
* @param integer $visitNo The visit number for which you
* want the SessionID
*
* @return int|null SessionID of candidate's nth visit, NULL if none found
*/
function getSessionID(int $visitNo): ?int
{
$timepoints = $this->data->timepoints;
if (isset($timepoints[$visitNo-1]) ) {
return intval(
strval($timepoints[$visitNo-1]->getSessionID())
);
}
return null;
}
/**
* Return a piece of data about this candidate
*
* @param string|null $var The type of data about the Candidate
* to be returned
*
* @return mixed The info requested
*/
public function getData(?string $var = null)
{
if (is_null($var)) {
return $this->candidateInfo;
} else {
return $this->candidateInfo[$var] ?? null;
}
}
/**
* Sets some data about the candidate and saves it into the
* database.
*
* @param array $newData Key-value pair(s) of the field(s) to change and the
* new value(s).
*
* @return bool
*
* @throws DatabaseException
* @throws LorisException
*/
public function setData(array $newData): bool
{
/* $newData should be in the form: array($key => $value). Count should
* equal 1 if this is the case.
*/
if (empty($newData)) {
throw new LorisException(
'Candidate::setData() cannot be called with an empty array!'
);
}
$this->candidateInfo = array_merge($this->candidateInfo, $newData);
\NDB_Factory::singleton()->database()->update(
'candidate',
$newData,
[
'CandID' => $this->getCandID(),
]
);
return true;
}
/**
* Returns the ProjectID for the current candidate
*
* @return \ProjectID RegistrationProjectID of candidate
*/
function getProjectID(): \ProjectID
{
return $this->data->registrationProjectID;
}
/**
* Returns the name of the candidate's project from the
* config file
*
* @return string Project name
*/
function getProjectTitle(): string
{
$ProjectList = Utility::getProjectList();
return $ProjectList[$this->getProjectID()->__toString()] ?? '';
}
/**
* Returns the CandID of this candidate
*
* @return integer 6 digit CandID
*/
function getCandID()
{
return $this->candidateInfo["CandID"];
}
/**
* Returns the PSCID of this candidate
*
* @return string The PSCID identifier for candidate
*/
function getPSCID(): string
{
return $this->candidateInfo["PSCID"];
}
/**
* Returns the site of this candidate
*
* @return string Site name of this candidate's site
*/
function getCandidateSite(): string
{
return $this->candidateInfo["PSC"];
}
/**
* Returns the ID of this candidate's site
*
* @return CenterID The numeric ID of the candidate's site
*/
function getCenterID(): CenterID
{
return $this->data->registrationCenterID;
}
/**
* Returns the date of birth of this candidate
*
* @return string|null The DoB in YYYY-MM-DD format
*/
function getCandidateDoB(): ?string
{
return $this->candidateInfo["DoB"];
}
/**
* Returns the way that the DoB should be displayed for this
* candidate to a user on the frontend.
*
* @return ?array{label:string,value:string}
*/
function getDisplayDoB(): ?array
{
if ($this->getCandidateDob() === null) {
return null;
}
$factory = NDB_Factory::singleton();
$config = $factory->config();
$dobFormat = $config->getSetting('dobFormat');
$dobDate = new DateTimeImmutable($this->getCandidateDoB());
switch ($dobFormat) {
case 'Ym':
return [
'label' => 'Date of Birth',
'value' => $dobDate->format('Y-m'),
];
case 'Ymd':
return [
'label' => 'Date of Birth',
'value' => $dobDate->format('Y-m-d'),
];
default:
throw new Exception("Unhandled DoB format: $dobFormat");
}
}
/**
* Returns the expect date of confinement (due date)
* of this candidate.
*
* @return string|null The DoB in YYYY-MM-DD format
*/
function getCandidateEDC(): ?string
{
return $this->candidateInfo["EDC"];
}
/**
* Return the candidate's sex
*
* @return ?Sex
*/
function getCandidateSex(): ?Sex
{
return $this->candidateInfo["Sex"];
}
/**
* Return the candidate's entity type.
*
* @return ?EntityType
*/
function getEntityType(): ?EntityType
{
return $this->candidateInfo["Entity_type"];
}
/**
* Return the candidate's ethnicity
*
* @return string The ethnicity of candidate
* @deprecated
*/
function getCandidateEthnicity(): string
{
return $this->candidateInfo["Ethnicity"];
}
/**
* Return whether the candidate is active
*
* @return string Y|N|null Active flag for this candidate
*/
function isActive(): string
{
return $this->candidateInfo["Active"];
}
/**
* Return the user that registered (created) this candidate
*
* @return string UserID of user who created this candidate.
*/
function registeredBy(): string
{
return $this->candidateInfo["RegisteredBy"];
}
/**
* Return the user who last changed this candidate
*
* @return string UserID of user who last changed this candidate
*/
function lastRecordChangeBy(): string
{
return $this->candidateInfo["UserID"];
}
/**
* Returns the list of visit labels w/ corresponding SessionID as key
*
* @return array Associative array in the format SessionID=>Visit_label
* @throws DatabaseException
*/
public function getListOfVisitLabels(): array
{
$factory = NDB_Factory::singleton();
//make sure it returns an array
$visitLabelArray = [];
$candID = $this->getCandID();
// make a local reference to the Database object
//
$db = $factory->database();
$query = "SELECT ID, Visit_label FROM session
WHERE CandID=:Candidate AND Active='Y' ORDER BY ID";
$result = $db->pselect($query, ['Candidate' => $candID]);
// map the array [VisitNo]=>Visit_label
foreach ($result as $row) {
$visitLabelArray[$row["ID"]] = $row["Visit_label"];
}
return $visitLabelArray;
}
/**
* Generates list of valid cohorts for a the selected Candidate's
* project
*
* @return array Array of the form CohortID => CohortID
* or NULL if none exist
* @throws DatabaseException
*/
public function getValidCohorts(): array
{
$subprojList = [];
$projID = $this->getProjectID();
$query = "SELECT CohortID
FROM project_cohort_rel
WHERE ProjectID = :prj";
$params = ['prj' => $projID];
$subproj = \NDB_Factory::singleton()
->database()
->pselect($query, $params);
foreach ($subproj as $row) {
foreach ($row as $key =>$val) {
if ($key == 'CohortID') {
$subprojList[$val] = $val;
}
}
}
return $subprojList;
}
/**
* Returns the CohortID and cohort title of the candidate's last visit
* based on Date_visit
*
* @return array|null Array with values CohortID and title
* for the candidate's last visit or NULL if none exist
*/
public function getCohortForMostRecentVisit(): ?array
{
$factory = NDB_Factory::singleton();
$db = $factory->database();
$candID = $this->getCandID();
$query = "SELECT CohortID, title FROM session
LEFT JOIN cohort USING (CohortID)
WHERE CandID=:cid AND Date_visit IS NOT NULL
ORDER BY Date_visit DESC LIMIT 1";
$where = ['cid' => $candID];
$result = $db->pselect($query, $where);
if (empty($result)) {
return null;
}
return $result[0];
}
/**
* Returns first visit for a candidate based on VisitNo
*
* @return string The visit label for the candidate's first visit
*/
public function getFirstVisit(): string
{
$factory = NDB_Factory::singleton();
$db = $factory->database();
$candID = $this->getCandID();
$query = "SELECT Visit_label FROM session
LEFT JOIN candidate USING (CandID)
WHERE CandID = :cid AND VisitNo = 1
AND Entity_type <> 'Scanner'";
$where = ['cid' => $candID];
try {
$result = $db->pselectOne($query, $where);
} catch (DomainException $ex) {
throw new LorisException(
"CandID: $candID has multiple first visits ".
"recorded whereas only 1 is expected."
);
}
return $result ?? '';
}
/**
* Returns the next visit number that should be created for this
* candidate.
*
* @return int The next visit number
*/
public function getNextVisitNo() : int
{
$factory = NDB_Factory::singleton();
$db = $factory->database();
$query = "SELECT MAX(s.VisitNo)+1
FROM candidate AS c
LEFT JOIN session AS s USING (CandID)
WHERE c.CandID=:CaID AND s.Active='Y' AND c.Active='Y'";
$result = $db->pselectOne($query, ['CaID' => $this->getCandID()]);
if ($result === null) {
return 1;
}
return intval($result);
}
/**
* Returns DateInterval between candidate's date of birth and a given date,
* or today if no date given.
*
* @param ?DateTime $refDate The reference date from which to calculate the age,
* or null if not provided
*
* @return DateInterval Between DoB and $refDate
*/
public function getAge(?DateTime $refDate = null): DateInterval
{
if (!$refDate) {
$refDate = new DateTime();
}
$dob = new DateTime($this->candidateInfo["DoB"]);
return $dob->diff($refDate);
}
/**
* Returns the candidate's calculated age today in int years
*
* @return int The candidate's age today as years
*/
public function getAgeInYears(): int
{
return (int)$this->getAge()->format('%y');
}
/**
* Returns the candidate's calculated age today in total number of months
*
* @return int The candidate's age today in months
*/
public function getAgeInMonths(): int
{
return (int)$this->getAge()->format('%m') +
12 * $this->getAgeInYears();
}
/**
* Returns the candidate's calculated age today in total number of days
*
* @return int The candidate's age today in days
*/
public function getAgeInDays(): int
{
return (int)$this->getAge()->days;
}
/**
* Returns list of consents and their respective statuses for this candidate
*
* @return array List of consents and their associated values for this candidate
* The keys of the arrays are the IDs of the consents
*/
public function getConsents(): array
{
$factory = NDB_Factory::singleton();
$db = $factory->database();
$candID = $this->getCandID();
$query = "SELECT ConsentID, Name, Status, DateGiven, DateWithdrawn, Label
FROM candidate_consent_rel cc JOIN consent c USING (ConsentID)
WHERE CandidateID=:cid";
$where = ['cid' => $candID];
$key = "ConsentID";
$consentList = $db->pselectWithIndexKey($query, $where, $key);
return $consentList;
}
/**
* Validate's that a PSCID matches the format defined by project
* config
*
* @param string $PSCID The PSCID to validate
* @param string $siteAbbrev The site of the candidate
* being validated to check
* against appropriate parts
* of PSCID definition
* @param string $projectAbbrev The project of the candidate
* being validated to check against appropriate
* parts of PSCID definition
*
* @return boolean True if PSCID is valid, false otherwise
*/
static public function validatePSCID(
string $PSCID,
string $siteAbbrev,
string $projectAbbrev
): bool {
$factory = NDB_Factory::singleton();
$config = $factory->config();
$PSCIDSettings = $config->getSetting('PSCID');
$regex = self::structureToPCRE(
$PSCIDSettings['structure'],
$siteAbbrev,
$projectAbbrev
);
//preg_match returns 1 on success.
return preg_match($regex, $PSCID) === 1;
}
/**
* Gets the participant_status options from participant_status_options table
*
* @return array Options array suitable for use in QuickForm select
* element
*/
static function getParticipantStatusOptions(): array
{
$DB = \NDB_Factory::singleton()->database();
$options = $DB->pselect(
"SELECT ID,Description
FROM participant_status_options
WHERE parentID IS NULL",
[]
);
$option_array = [];
foreach ($options as $option) {
$option_array[$option['ID']] = $option['Description'];
}
return $option_array;
}