IcingaTimePeriod: add and test isActive() method

This commit is contained in:
Thomas Gelf 2016-05-18 21:21:53 +02:00
parent c65c8a72c7
commit 2ae326ab8c
3 changed files with 105 additions and 0 deletions

View File

@ -39,4 +39,21 @@ class IcingaTimePeriod extends IcingaObject
// @codingStandardsIgnoreEnd
return c::renderKeyValue('update', $this->update_method);
}
public function isActive($now = null)
{
if ($now === null) {
$now = time();
}
foreach ($this->ranges()->getRanges() as $range) {
if ($range->isActive($now)) {
return true;
}
}
// TODO: no range currently means (and renders) "never", Icinga behaves
// different. Figure out whether and how we should support this
return false;
}
}

View File

@ -17,4 +17,73 @@ class IcingaTimePeriodRange extends DbObject
'range_type' => 'include',
'merge_behaviour' => 'set',
);
public function isActive($now = null)
{
if ($now === null) {
$now = time();
}
if (false === ($wday = $this->getWeekDay($this->timeperiod_key))) {
// TODO, dates are not yet supported
return false;
}
$wdayName = $this->timeperiod_key;
if ((int) strftime('%w', $now) !== $wday) {
return false;
}
$timeRanges = preg_split('/\s*,\s*/', $this->timeperiod_value, -1, PREG_SPLIT_NO_EMPTY);
foreach ($timeRanges as $timeRange) {
if ($this->timeRangeIsActive($timeRange, $now)) {
return true;
}
}
return false;
}
protected function timeRangeIsActive($rangeString, $now)
{
if (sscanf($rangeString, '%2d:%2d-%2d:%2d', $hBegin, $mBegin, $hEnd, $mEnd) === 4) {
if ($this->timeFromHourMin($hBegin, $mBegin, $now) <= $now
&& $this->timeFromHourMin($hEnd, $mEnd, $now) >= $now
) {
return true;
}
} else {
// TODO: throw exception?
}
return false;
}
protected function timeFromHourMin($hour, $min, $now)
{
return strtotime(sprintf('%s %02d:%02d:00', date('Y-m-d', $now), $hour, $min));
}
protected function getWeekDay($day)
{
switch ($day) {
case 'sunday':
return 0;
case 'monday':
return 1;
case 'tuesday':
return 2;
case 'wednesday':
return 3;
case 'thursday':
return 4;
case 'friday':
return 5;
case 'saturday':
return 6;
}
return false;
}
}

View File

@ -79,6 +79,25 @@ class IcingaTimePeriodTest extends BaseTestCase
return $object;
}
public function testIsActiveWorksForWeekdayRanges()
{
$period = $this->createTestPeriod();
$newRanges = array(
'monday' => '00:00-24:00',
'tuesday' => '18:00-24:00',
'wednesday' => '00:00-24:00',
);
$period->ranges = $newRanges;
// Tuesday:
$this->assertFalse($period->isActive(strtotime('2016-05-17 10:00:00')));
// Wednesday:
$this->assertTrue($period->isActive(strtotime('2016-05-18 10:00:00')));
// Thursday:
$this->assertFalse($period->isActive(strtotime('2016-05-19 10:00:00')));
}
protected function loadTestPeriod()
{
return IcingaTimePeriod::load($this->testPeriodName, $this->getDb());