summaryrefslogtreecommitdiffstats
path: root/library/Reporting/Web/Forms/TimeframeForm.php
blob: 37ea34f627e418bc1a0833b4db2fefecac6e14ea (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
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
<?php

// Icinga Reporting | (c) 2019 Icinga GmbH | GPLv2

namespace Icinga\Module\Reporting\Web\Forms;

use DateTime;
use Exception;
use Icinga\Module\Reporting\Database;
use ipl\Html\Contract\FormSubmitElement;
use ipl\Html\FormElement\LocalDateTimeElement;
use ipl\Html\HtmlDocument;
use ipl\Validator\CallbackValidator;
use ipl\Web\Compat\CompatForm;

class TimeframeForm extends CompatForm
{
    /** @var int */
    protected $id;

    /**
     * Create a new form instance with the given report
     *
     * @param int $id
     *
     * @return static
     */
    public static function fromId(int $id): self
    {
        $form = new static();

        $form->id = $id;

        return $form;
    }

    public function hasBeenSubmitted(): bool
    {
        return $this->hasBeenSent() && ($this->getPopulatedValue('submit') || $this->getPopulatedValue('remove'));
    }

    protected function assemble()
    {
        $this->addElement('text', 'name', [
            'required'    => true,
            'label'       => $this->translate('Name'),
            'description' => $this->translate('A unique name of this timeframe')
        ]);

        $default = new DateTime('00:00:00');
        $start = $this->getPopulatedValue('start', $default);
        if (! $start instanceof DateTime) {
            $datetime = DateTime::createFromFormat(LocalDateTimeElement::FORMAT, $start);
            if ($datetime) {
                $start = $datetime;
            }
        }

        $relativeStart = $this->getPopulatedValue('relative-start', $start instanceof DateTime ? 'n' : 'y');
        $this->addElement('checkbox', 'relative-start', [
            'required' => false,
            'class'    => 'autosubmit',
            'value'    => $relativeStart,
            'label'    => $this->translate('Relative Start')
        ]);

        if ($relativeStart === 'n') {
            if (! $start instanceof DateTime) {
                $start = $default;
                $this->clearPopulatedValue('start');
            }

            $this->addElement(
                new LocalDateTimeElement('start', [
                    'required'    => true,
                    'value'       => $start,
                    'label'       => $this->translate('Start'),
                    'description' => $this->translate('Specifies the start time of this timeframe')
                ])
            );
        } else {
            $this->addElement('text', 'start', [
                'required'    => true,
                'label'       => $this->translate('Start'),
                'placeholder' => $this->translate('First day of this month'),
                'description' => $this->translate('Specifies the start time of this timeframe'),
                'validators' => [
                    new CallbackValidator(function ($value, CallbackValidator $validator) {
                        if ($value !== null) {
                            try {
                                new DateTime($value);
                            } catch (Exception $_) {
                                $validator->addMessage($this->translate('Invalid textual date time'));

                                return false;
                            }
                        }

                        return true;
                    })
                ]
            ]);
        }

        $default = new DateTime('23:59:59');
        $end = $this->getPopulatedValue('end', $default);
        if (! $end instanceof DateTime) {
            $datetime = DateTime::createFromFormat(LocalDateTimeElement::FORMAT, $end);
            if ($datetime) {
                $end = $datetime;
            }
        }

        $relativeEnd = $this->getPopulatedValue('relative-end', $end instanceof DateTime ? 'n' : 'y');
        if ($relativeStart === 'y') {
            $this->addElement('checkbox', 'relative-end', [
                'required' => false,
                'class'    => 'autosubmit',
                'value'    => $relativeEnd,
                'label'    => $this->translate('Relative End')
            ]);
        }

        if ($relativeEnd === 'n' || $relativeStart === 'n') {
            if (! $end instanceof DateTime) {
                $end = $default;
                $this->clearPopulatedValue('end');
            }

            $this->addElement(
                new LocalDateTimeElement('end', [
                    'required'    => true,
                    'value'       => $end,
                    'label'       => $this->translate('End'),
                    'description' => $this->translate('Specifies the end time of this timeframe')
                ])
            );
        } else {
            $this->addElement('text', 'end', [
                'required'    => true,
                'label'       => $this->translate('End'),
                'placeholder' => $this->translate('Last day of this month'),
                'description' => $this->translate('Specifies the end time of this timeframe'),
                'validators' => [
                    new CallbackValidator(function ($value, CallbackValidator $validator) {
                        if ($value !== null) {
                            try {
                                new DateTime($value);
                            } catch (Exception $_) {
                                $validator->addMessage($this->translate('Invalid textual date time'));

                                return false;
                            }
                        }

                        return true;
                    })
                ]
            ]);
        }

        $this->addElement('submit', 'submit', [
            'label' => $this->id === null
                ? $this->translate('Create Time Frame')
                : $this->translate('Update Time Frame')
        ]);

        if ($this->id !== null) {
            /** @var FormSubmitElement $removeButton */
            $removeButton = $this->createElement('submit', 'remove', [
                'label'          => $this->translate('Remove Time Frame'),
                'class'          => 'btn-remove',
                'formnovalidate' => true
            ]);
            $this->registerElement($removeButton);

            /** @var HtmlDocument $wrapper */
            $wrapper = $this->getElement('submit')->getWrapper();
            $wrapper->prepend($removeButton);
        }
    }

    public function onSuccess()
    {
        $db = Database::get();

        if ($this->getPopulatedValue('remove')) {
            $db->delete('timeframe', ['id = ?' => $this->id]);

            return;
        }

        $values = $this->getValues();
        if ($values['start'] instanceof DateTime) {
            $values['start'] = $values['start']->format(LocalDateTimeElement::FORMAT);
        }

        if ($values['end'] instanceof DateTime) {
            $values['end'] = $values['end']->format(LocalDateTimeElement::FORMAT);
        }

        $now = time() * 1000;

        $end = $db->quoteIdentifier('end');

        if ($this->id === null) {
            $db->insert('timeframe', [
                'name'  => $values['name'],
                'start' => $values['start'],
                $end    => $values['end'],
                'ctime' => $now,
                'mtime' => $now
            ]);
        } else {
            $db->update('timeframe', [
                'name'  => $values['name'],
                'start' => $values['start'],
                $end    => $values['end'],
                'mtime' => $now
            ], ['id = ?' => $this->id]);
        }
    }
}