summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/web/src/FormElement/ScheduleElement/MonthlyFields.php
blob: 26329fc1bebe3fc34ae5b416fc33c850c8e9c7c8 (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
<?php

namespace ipl\Web\FormElement\ScheduleElement;

use ipl\Html\Attributes;
use ipl\Html\FormElement\FieldsetElement;
use ipl\Html\HtmlElement;
use ipl\Validator\CallbackValidator;
use ipl\Validator\InArrayValidator;
use ipl\Validator\ValidatorChain;
use ipl\Web\FormElement\ScheduleElement\Common\FieldsProtector;
use ipl\Web\FormElement\ScheduleElement\Common\FieldsUtils;

class MonthlyFields extends FieldsetElement
{
    use FieldsUtils;
    use FieldsProtector;

    /** @var string Used as radio option to run each selected days/months */
    public const RUNS_EACH = 'each';

    /** @var string Used as radio option to build complex job schedules */
    public const RUNS_ONTHE = 'onthe';

    /** @var int Number of days in a week */
    public const WEEK_DAYS = 7;

    /** @var int Day of the month to preselect by default */
    protected $default = 1;

    /** @var int Number of fields to render */
    protected $availableFields;

    protected function init(): void
    {
        parent::init();
        $this->initUtils();

        $this->availableFields = (int) date('t');
    }

    /**
     * Set the available fields/days of the month to be rendered
     *
     * @param int $fields
     *
     * @return $this
     */
    public function setAvailableFields(int $fields): self
    {
        $this->availableFields = $fields;

        return $this;
    }

    /**
     * Set the default field/day to be selected
     *
     * @param int $default
     *
     * @return $this
     */
    public function setDefault(int $default): self
    {
        $this->default = $default;

        return $this;
    }

    /**
     * Get all the selected weekdays
     *
     * @return array
     */
    public function getSelectedDays(): array
    {
        $selectedDays = [];
        foreach (range(1, $this->availableFields) as $day) {
            if ($this->getValue("day$day", 'n') === 'y') {
                $selectedDays[] = $day;
            }
        }

        if (empty($selectedDays)) {
            $selectedDays[] = $this->default;
        }

        return $selectedDays;
    }

    protected function assemble()
    {
        $this->getAttributes()->set('id', $this->protectId('monthly-fields'));

        $runsOn = $this->getPopulatedValue('runsOn', static::RUNS_EACH);
        $this->addElement('radio', 'runsOn', [
            'required' => true,
            'class'    => 'autosubmit',
            'value'    => $runsOn,
            'options'  => [static::RUNS_EACH => $this->translate('Each')],
        ]);

        $listItems = HtmlElement::create('ul', ['class' => ['schedule-element-fields', 'multiple-fields']]);
        if ($runsOn === static::RUNS_ONTHE) {
            $listItems->getAttributes()->add('class', 'disabled');
        }

        foreach (range(1, $this->availableFields) as $day) {
            $checkbox = $this->createElement('checkbox', "day$day", [
                'class' => ['autosubmit', 'sr-only'],
                'value' => $day === $this->default && $runsOn === static::RUNS_EACH
            ]);
            $this->registerElement($checkbox);

            $htmlId = $this->protectId("day$day");
            $checkbox->getAttributes()->set('id', $htmlId);

            $listItem = HtmlElement::create('li');
            $listItem->addHtml($checkbox, HtmlElement::create('label', ['for' => $htmlId], $day));
            $listItems->addHtml($listItem);
        }

        $monthlyWrapper = HtmlElement::create('div', ['class' => 'monthly']);
        $runsEach = $this->getElement('runsOn');
        $runsEach->prependWrapper($monthlyWrapper);
        $monthlyWrapper->addHtml($runsEach, $listItems);

        $this->addElement('radio', 'runsOn', [
            'required'   => $runsOn !== static::RUNS_EACH,
            'class'      => 'autosubmit',
            'options'    => [static::RUNS_ONTHE => $this->translate('On the')],
            'validators' => [
                new InArrayValidator([
                    'strict'   => true,
                    'haystack' => [static::RUNS_EACH, static::RUNS_ONTHE]
                ])
            ]
        ]);

        $ordinalWrapper = HtmlElement::create('div', ['class' => 'ordinal']);
        $runsOnThe = $this->getElement('runsOn');
        $runsOnThe->prependWrapper($ordinalWrapper);
        $ordinalWrapper->addHtml($runsOnThe);

        $enumerations = $this->createOrdinalElement();
        $enumerations->getAttributes()->set('disabled', $runsOn === static::RUNS_EACH);
        $this->registerElement($enumerations);

        $selectableDays = $this->createOrdinalSelectableDays();
        $selectableDays->getAttributes()->set('disabled', $runsOn === static::RUNS_EACH);
        $this->registerElement($selectableDays);

        $ordinalWrapper->addHtml($enumerations, $selectableDays);
    }

    protected function registerAttributeCallbacks(Attributes $attributes)
    {
        parent::registerAttributeCallbacks($attributes);

        $attributes
            ->registerAttributeCallback('default', null, [$this, 'setDefault'])
            ->registerAttributeCallback('availableFields', null, [$this, 'setAvailableFields'])
            ->registerAttributeCallback('protector', null, [$this, 'setIdProtector']);
    }

    protected function addDefaultValidators(ValidatorChain $chain): void
    {
        $chain->add(
            new CallbackValidator(function ($_, CallbackValidator $validator): bool {
                if ($this->getValue('runsOn', static::RUNS_EACH) !== static::RUNS_EACH) {
                    return true;
                }

                $valid = false;
                foreach (range(1, $this->availableFields) as $day) {
                    if ($this->getValue("day$day") === 'y') {
                        $valid = true;

                        break;
                    }
                }

                if (! $valid) {
                    $validator->addMessage($this->translate('You must select at least one of these days'));
                }

                return $valid;
            })
        );
    }
}