From 9a4ffe5fdda25b67dfe066bc107ee497b8ff52e0 Mon Sep 17 00:00:00 2001 From: regis Date: Tue, 20 Dec 2022 09:03:59 -0500 Subject: [PATCH] Valid date message when date is invalid (#8279) When using /api/v0.0.3/candidates with an invalid date format, returns 400 Bad Requests/JSON errors. This checks the date of birth and returns the correct format in the message ('yyyy-mm-dd') and returns an appropriate error message if the check fails. --- modules/api/php/endpoints/candidates.class.inc | 2 +- php/libraries/Candidate.class.inc | 13 +++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/modules/api/php/endpoints/candidates.class.inc b/modules/api/php/endpoints/candidates.class.inc index 8914434ebfd..b820ccaca6e 100644 --- a/modules/api/php/endpoints/candidates.class.inc +++ b/modules/api/php/endpoints/candidates.class.inc @@ -241,7 +241,7 @@ class Candidates extends Endpoint implements \LORIS\Middleware\ETagCalculator $pscid, $project->getId() ); - } catch (\LorisException $e) { + } catch (\LorisException | \InvalidArgumentException $e) { return new \LORIS\Http\Response\JSON\BadRequest($e->getMessage()); } diff --git a/php/libraries/Candidate.class.inc b/php/libraries/Candidate.class.inc index 6803995bb94..87f81c0ba56 100644 --- a/php/libraries/Candidate.class.inc +++ b/php/libraries/Candidate.class.inc @@ -18,6 +18,7 @@ define('PSCID_NOT_UNIQUE', 3); define('PSCID_INVALID_STRUCTURE', 4); define('EDC_NOT_SPECIFIED', 5); define('DOB_NOT_SPECIFIED', 6); +define('DOB_INVALID', 7); /** * Wrapper around a candidate in Loris. Mostly, it gets information @@ -273,15 +274,19 @@ class Candidate implements \LORIS\StudyEntities\AccessibleResource, EDC_NOT_SPECIFIED ); } - if ($dateOfBirth !== null - && (DateTime::createFromFormat('Y-m-d', $dateOfBirth) === false - || empty($dateOfBirth)) - ) { + if (empty($dateOfBirth)) { throw new InvalidArgumentException( "Date of Birth must be specified", DOB_NOT_SPECIFIED ); } + $dob = DateTime::createFromFormat('!Y-m-d', $dateOfBirth); + if ($dob === false) { + throw new InvalidArgumentException( + "Date of Birth is invalid (expected format: YYYY-MM-DD)", + DOB_INVALID + ); + } if ($PSCIDSettings['generation'] == 'user') { // check pscid is specified