Background
I'm integrating Limesurvey with an application, where new survey tokens are added directly to the Limesurvey database. Before insertion can be done, I need to check that a given set of tokens (with validfrom
and validuntil
attributes) in Limesurvey does not intersect with a given range of dates (DateTime
).
The problem
Since Limesurveys token validfrom
and validuntil
attributes can be NULL
, a simple comparison of DateTime
can't be done, or can it?
(A Limesurvey validfrom/validuntil
NULL
value implies "always")
What I have
A php class that checks if the Limesurvey attributes are NULL
(or not), and returning a calculation of the intersection as needed.
Code: http://phpfiddle.org/main/code/3vp-j3b
(It's what's inside the foreach
loop, lines 34-70, that are interesting here)
What I ask
Is there a way to improve/optimise this method, given that the comparison values are special?
You could replace null with a possible first and last date to ease comparing:
if (is_null($token['validfrom']) {
$token_validfrom = new DateTime('0000-01-01 00:00:00');
} else {
$token_validfrom = new DateTime($token['validfrom']);
}
if (is_null($token['validuntil']) {
$token_validuntil = new DateTime('9999-12-31 23:23:59');
} else {
$token_validuntil = new DateTime($token['validuntil']);
}
This way only your last line of comparison should be necessary:
return ($validfrom == $token_validfrom) || ($validfrom > $token_validfrom ? $validfrom < $token_validuntil : $token_validfrom < $validuntil);