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

namespace ipl\Web\FormElement\ScheduleElement;

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

class WeeklyFields extends FieldsetElement
{
    use FieldsProtector;

    /** @var array A list of valid week days */
    protected $weekdays = [];

    /** @var string A valid weekday to be selected by default */
    protected $default = 'MO';

    public function __construct($name, $attributes = null)
    {
        $this->weekdays = [
            'MO' => $this->translate('Mon'),
            'TU' => $this->translate('Tue'),
            'WE' => $this->translate('Wed'),
            'TH' => $this->translate('Thu'),
            'FR' => $this->translate('Fri'),
            'SA' => $this->translate('Sat'),
            'SU' => $this->translate('Sun')
        ];

        parent::__construct($name, $attributes);
    }

    /**
     * Set the default weekday to be preselected
     *
     * @param string $default
     *
     * @return $this
     */
    public function setDefault(string $default): self
    {
        $weekday = strlen($default) > 2 ? substr($default, 0, -1) : $default;
        if (! isset($this->weekdays[strtoupper($weekday)])) {
            throw new InvalidArgumentException(sprintf('Invalid weekday provided: %s', $default));
        }

        $this->default = strtoupper($weekday);

        return $this;
    }

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

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

        return $selectedDays;
    }

    /**
     * Transform the given weekdays into key=>value array that can be populated
     *
     * @param array $weekdays
     *
     * @return array
     */
    public function loadWeekDays(array $weekdays): array
    {
        $values = [];
        foreach ($this->weekdays as $weekday => $_) {
            $values[$weekday] = in_array($weekday, $weekdays, true) ? 'y' : 'n';
        }

        return $values;
    }

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

        $fieldsWrapper = HtmlElement::create('div', ['class' => 'weekly']);
        $listItems = HtmlElement::create('ul', ['class' => ['schedule-element-fields', 'multiple-fields']]);

        foreach ($this->weekdays as $day => $value) {
            $checkbox = $this->createElement('checkbox', $day, [
                'class' => ['autosubmit', 'sr-only'],
                'value' => $day === $this->default
            ]);
            $this->registerElement($checkbox);

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

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

        $fieldsWrapper->addHtml($listItems);
        $this->addHtml($fieldsWrapper);
    }

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

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

    protected function addDefaultValidators(ValidatorChain $chain): void
    {
        $chain->add(
            new CallbackValidator(function ($_, CallbackValidator $validator): bool {
                $valid = false;
                foreach ($this->weekdays as $weekday => $_) {
                    if ($this->getValue($weekday) === 'y') {
                        $valid = true;

                        break;
                    }
                }

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

                return $valid;
            })
        );
    }
}