summaryrefslogtreecommitdiffstats
path: root/library/Director/Objects/IcingaTimePeriodRange.php
blob: 55c1a3ee57dc6bc86605757b5f7f144abfa11623 (plain)
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
<?php

namespace Icinga\Module\Director\Objects;

use Icinga\Module\Director\Data\Db\DbObject;

class IcingaTimePeriodRange extends DbObject
{
    protected $keyName = array('timeperiod_id', 'range_key', 'range_type');

    protected $table = 'icinga_timeperiod_range';

    protected $defaultProperties = array(
        'timeperiod_id'   => null,
        'range_key'       => null,
        'range_value'     => null,
        'range_type'      => 'include',
        'merge_behaviour' => 'set',
    );

    public function isActive($now = null)
    {
        if ($now === null) {
            $now = time();
        }

        if (false === ($weekDay = $this->getWeekDay($this->get('range_key')))) {
            // TODO, dates are not yet supported
            return false;
        }

        if ((int) date('w', $now) !== $weekDay) {
            return false;
        }

        $timeRanges = preg_split('/\s*,\s*/', $this->get('range_value'), -1, PREG_SPLIT_NO_EMPTY);
        foreach ($timeRanges as $timeRange) {
            if ($this->timeRangeIsActive($timeRange, $now)) {
                return true;
            }
        }

        return false;
    }

    protected function timeRangeIsActive($rangeString, $now)
    {
        $hBegin = $mBegin = $hEnd = $mEnd = null;
        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;
    }
}