DateTimeRangeButton::getRangeTimes()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 11
rs 9.9666
cc 1
nc 1
nop 0
1
<?php
2
3
namespace kalanis\kw_table\form_nette_lte\Controls;
4
5
6
use kalanis\kw_table\form_nette_lte\Helper\DateTimeRangeButtonItem;
7
use Nette\Forms\Container;
8
use Nette\Utils\Html;
9
use Nette\Utils\DateTime;
10
11
12
class DateTimeRangeButton extends DateTimeRange
13
{
14
    protected ?Html $span;
15
    protected $script;
16
    /** @var string */
17
    protected string $uniqueInputId = '';
18
    protected $value;
19
20
    public function __construct(string $name, $label = null, $maxLength = null, $searchFormat = null, \DateTime $startTime = null, \DateTime $endTime = null)
21
    {
22
        $this->uniqueId = strval(uniqid('adminLteDateTimeRange'));
23
        $this->uniqueInputId = $this->uniqueId . 'Input';
24
        parent::__construct($name, $label, $maxLength, $searchFormat, $startTime, $endTime);
25
    }
26
27
    /**
28
     * @return DateTimeRangeButtonItem[]
29
     */
30
    public static function getRangeTimes()
31
    {
32
        return [
33
            _('All')          => new DateTimeRangeButtonItem(_('All'), 'moment().subtract(1, \'days\').hour(0).minute(0).seconds(0).millisecond(0)', 'moment().add(1, \'days\').hour(23).minute(55).seconds(0).millisecond(0)', null, null),
34
            _('Next 7 days')  => new DateTimeRangeButtonItem(_('Next 7 days'), 'moment().hour(0).minute(0).seconds(0).millisecond(0)', 'moment().add(6, \'days\').hour(23).minute(55).seconds(0).millisecond(0)', 'today', '+6days'),
35
            _('Today')        => new DateTimeRangeButtonItem(_('Today'), 'moment().hour(0).minute(0).seconds(0).millisecond(0)', 'moment().hour(23).minute(55).seconds(0).millisecond(0)', 'today', 'today'),
36
            _('Yesterday')    => new DateTimeRangeButtonItem(_('Yesterday'), 'moment().subtract(1, \'days\').hour(0).minute(0).seconds(0).millisecond(0)', 'moment().subtract(1, \'days\').hour(23).minute(55).seconds(0).millisecond(0)', 'yesterday', 'yesterday'),
37
            _('Last 7 days')  => new DateTimeRangeButtonItem(_('Last 7 days'), 'moment().hour(0).minute(0).seconds(0).millisecond(0).subtract(6, \'days\')', 'moment().hour(23).minute(55).seconds(0).millisecond(0)', '-7days', 'today'),
38
            _('Last 30 days') => new DateTimeRangeButtonItem(_('Last 30 days'), 'moment().hour(0).minute(0).seconds(0).millisecond(0).subtract(29, \'days\')', 'moment().hour(23).minute(55).seconds(0).millisecond(0)', '-30days', 'today'),
39
            _('This month')   => new DateTimeRangeButtonItem(_('This month'), 'moment().startOf(\'month\').hour(0).minute(0).seconds(0).millisecond(0)', 'moment().endOf(\'month\').hour(23).minute(55).seconds(0).millisecond(0)', 'first day of this month', 'last day of this  month'),
40
            _('Last month')   => new DateTimeRangeButtonItem(_('Last month'), 'moment().subtract(1, \'month\').startOf(\'month\').hour(0).minute(0).seconds(0).millisecond(0)', 'moment().subtract(1, \'month\').endOf(\'month\').hour(23).minute(55).seconds(0).millisecond(0)', 'first day of last month', 'last day of last month'),
41
        ];
42
    }
43
44
    public function getValue()
45
    {
46
        $startValue = $endValue = null;
47
        $named = static::getRangeTimes();
48
        $namedKeys = array_keys($named);
49
        if (in_array($this->value, $namedKeys)) {
50
            $startRange = $named[$this->value]->startTime;
51
            if ($startRange) {
52
                $start = new DateTime($startRange);
53
                $start->setTime(0, 0, 0);
54
                $startValue = $start->format($this->searchFormat);
55
            }
56
            $endRange = $named[$this->value]->endTime;
57
            if ($endRange) {
58
                $end = new DateTime($endRange);
59
                $end->setTime(23, 59, 59);
60
                $endValue = $end->format($this->searchFormat);
61
            }
62
        }
63
        if (!$startValue && !empty($this->startValue)) {
64
            $startValue = $this->startValue->format($this->searchFormat);
65
        };
66
        if (!$endValue && !empty($this->endValue)) {
67
            $endValue = $this->endValue->format($this->searchFormat);
68
        }
69
70
        return [
71
            0 => $startValue,
72
            1 => $endValue
73
        ];
74
    }
75
76
    public function setValue($value)
77
    {
78
        $this->value = $value;
79
        $exploded = explode('-', $value, 2);
80
        if (1 < count($exploded)) {
81
            $this->startValue = new \DateTime(trim($exploded[0]));
82
            $this->endValue = new \DateTime(trim($exploded[1]));
83
        }
84
85
        if ($this->started) {
86
            $this->input->addAttributes(['value' => $value]);
0 ignored issues
show
Bug introduced by
The method addAttributes() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

86
            $this->input->/** @scrutinizer ignore-call */ 
87
                          addAttributes(['value' => $value]);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
87
            $named = static::getRangeTimes();
88
            $namedKeys = array_keys($named);
89
            if (in_array($value, $namedKeys)) {
90
                $this->span->removeChildren();
0 ignored issues
show
Bug introduced by
The method removeChildren() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

90
                $this->span->/** @scrutinizer ignore-call */ 
91
                             removeChildren();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
91
                $this->span->addText($value);
92
93
                $addedScriptText = '$(\'#' . $this->uniqueId . '\').data(\'daterangepicker\').setStartDate(' . $named[$value]->startJs . ');
94
								$(\'#' . $this->uniqueId . '\').data(\'daterangepicker\').setEndDate(' . $named[$value]->endJs . ');';
95
                $script = $this->setScriptText($addedScriptText);
96
            } else {
97
                $this->span->removeChildren();
98
                $this->span->addText($value);
99
100
                $addedScriptText = '';
101
                if ($this->startValue) {
102
                    $addedScriptText .= '    $(\'#' . $this->uniqueId . '\').data(\'daterangepicker\').setStartDate(moment("' . $this->startValue->format('Y-m-d H:i') . '"));';
103
                }
104
                if ($this->endValue) {
105
                    $addedScriptText .= '    $(\'#' . $this->uniqueId . '\').data(\'daterangepicker\').setEndDate(moment("' . $this->endValue->format('Y-m-d H:i') . '"));';
106
                }
107
                $script = $this->setScriptText($addedScriptText);
108
            }
109
            $this->control->offsetUnset(2);
110
            $this->control->insert(2, $script);
111
        }
112
    }
113
114
    protected function setControlHtml(string $name)
115
    {
116
        $divGroup = Html::el('div', ['class' => "input-group dateTimeRangeButtonDiv"]);
117
        $button = Html::el('button', ['class' => "btn btn-default pull-right", 'type' => "button", 'id' => $this->uniqueId]);
118
        $span = $this->span = Html::el('span');
119
//        $iCalendar = Html::el('i', ['class' => "fa fa-calendar"]);
120
        $spanText = _('All');
121
        $iCaret = Html::el('i', ['class' => "fa fa-caret-down"]);
122
123
        $rangeTimes = static::getRangeTimes();
124
        $addedScriptText = '$(\'#' . $this->uniqueId . '\').data(\'daterangepicker\').setStartDate(' . $rangeTimes[_('All')]->startJs . ');
125
							$(\'#' . $this->uniqueId . '\').data(\'daterangepicker\').setEndDate(' . $rangeTimes[_('All')]->endJs . ');';
126
        $script = $this->setScriptText($addedScriptText);
127
128
        $input = $this->input = Html::el('input', [
129
            'type' => 'hidden',
130
            'name' => $name,
131
            'id'   => $this->uniqueInputId
132
        ]);
133
134
        // $span->addHtml($iCalendar);
135
        $span->addText($spanText);
136
        $button->addHtml($span);
137
        $button->addHtml($iCaret);
138
        $divGroup->addHtml($button);
139
        $divGroup->addHtml($input);
140
        $divGroup->addHtml($script);
141
        $this->control = $divGroup;
0 ignored issues
show
Bug introduced by
The property control is declared read-only in Nette\Forms\Controls\BaseControl.
Loading history...
142
    }
143
144
    private function setScriptText($addedScriptText = null)
145
    {
146
        $rangeTimes = static::getRangeTimes();
147
        $rangeText = null;
148
        foreach ($rangeTimes AS $key => $jsMomentTimes) {
149
            $rangeText .= '\'' . $key . '\': [' . $jsMomentTimes->startJs . ', ' . $jsMomentTimes->endJs . "],\n";
150
        }
151
        $scriptText = "	document.addEventListener('DOMContentLoaded', function() {";
152
        $scriptText .= "	$('#" . $this->uniqueId . "').daterangepicker(
153
							{
154
								ranges: {" . $rangeText . "},
155
								locale: { 
156
								    customRangeLabel: '" . _('Own range') . "', 
157
								    applyLabel: '" . _('Use') . "', 
158
								    cancelLabel: '" . _('Cancel') . "', 
159
                                },
160
                                timePicker: true, 
161
                                timePickerIncrement: 5, 
162
                                format: 'MM/DD/YYYY h:mm A',
163
                                //opens: 'right',
164
							},
165
							function (start, end, label) {
166
								if(label == '" . _('Own range') . "'){
167
									$('#" . $this->uniqueId . " span')
168
										.html(start.format('DD.MM.YYYY') + ' - ' + end.format('DD.MM.YYYY'));
169
									$('#" . $this->uniqueInputId . "')
170
										.val(start.format('DD.MM.YYYY 00:00:00') + ' - ' + end.format('DD.MM.YYYY 23:59:59'))
171
										.trigger('change');
172
								} else {
173
									if(label == '" . _('All') . "'){
174
										$('#" . $this->uniqueId . "').val('');
175
									}
176
									$('#" . $this->uniqueId . " span')
177
										.html(label);
178
										
179
									$('#" . $this->uniqueInputId . "')
180
										.val(label)
181
										.trigger('change');
182
								}
183
							}
184
						);
185
						$('.dateTimeRangeButtonDiv input').change(function() {
186
							$(this).parents('form').submit();
187
						});";
188
        if ($addedScriptText) {
189
            $scriptText .= $addedScriptText . "\n";
190
        }
191
        $scriptText .= "}, false);";
192
        $this->script = Html::el('script')->addHtml($scriptText);
193
        return $this->script;
194
    }
195
196
    public static function register(?string $searchFormat = null, ?\DateTime $startTime = null, ?\DateTime $endTime = null)
197
    {
198
        Container::extensionMethod('addDateTimeRangeButton', function ($container, $name, $label = null, $maxLength = null, $searchFormat = null, \DateTime $startTime = null, \DateTime $endTime = null) {
199
            $picker = $container[$name] = new DateTimeRangeButton($name, $label, $maxLength, $searchFormat, $startTime, $endTime);
200
            return $picker;
201
        });
202
    }
203
}
204