Debian Codegraph @

vendor/ipl/web/src/FormElement/ScheduleElement/Common/FieldsUtils.php

raw
1 <?php
2
3 namespace ipl\Web\FormElement\ScheduleElement\Common;
4
5 use DateInterval;
6 use DateTime;
7 use Exception;
8 use InvalidArgumentException;
9 use ipl\Html\Contract\FormElement;
10 use ipl\Scheduler\RRule;
11 use ipl\Web\FormElement\ScheduleElement\MonthlyFields;
12
13 trait FieldsUtils
14 {
15 // Non-standard frequency options
16 public static $everyDay = 'day';
17 public static $everyWeekday = 'weekday';
18 public static $everyWeekend = 'weekend';
19
20 // Enumerators for the monthly and annually schedule of a custom frequency
21 public static $first = 'first';
22 public static $second = 'second';
23 public static $third = 'third';
24 public static $fourth = 'fourth';
25 public static $fifth = 'fifth';
26 public static $last = 'last';
27
28 private $regulars = [];
29
30 protected function initUtils(): void
31 {
32 $this->regulars = [
33 'MO' => $this->translate('Monday'),
34 'TU' => $this->translate('Tuesday'),
35 'WE' => $this->translate('Wednesday'),
36 'TH' => $this->translate('Thursday'),
37 'FR' => $this->translate('Friday'),
38 'SA' => $this->translate('Saturday'),
39 'SU' => $this->translate('Sunday')
40 ];
41 }
42
43 protected function createOrdinalElement(): FormElement
44 {
45 return $this->createElement('select', 'ordinal', [
46 'class' => 'autosubmit',
47 'value' => $this->getPopulatedValue('ordinal', static::$first),
48 'options' => [
49 static::$first => $this->translate('First'),
50 static::$second => $this->translate('Second'),
51 static::$third => $this->translate('Third'),
52 static::$fourth => $this->translate('Fourth'),
53 static::$fifth => $this->translate('Fifth'),
54 static::$last => $this->translate('Last')
55 ]
56 ]);
57 }
58
59 protected function createOrdinalSelectableDays(): FormElement
60 {
61 $select = $this->createElement('select', 'day', [
62 'class' => 'autosubmit',
63 'value' => $this->getPopulatedValue('day', static::$everyDay),
64 'options' => $this->regulars + [
65 'separator' => '──────────────────────────',
66 static::$everyDay => $this->translate('Day'),
67 static::$everyWeekday => $this->translate('Weekday (Mon - Fri)'),
68 static::$everyWeekend => $this->translate('WeekEnd (Sat or Sun)')
69 ]
70 ]);
71 $select->getOption('separator')->getAttributes()->set('disabled', true);
72
73 return $select;
74 }
75
76 /**
77 * Load the given RRule instance into a list of key=>value pairs
78 *
79 * @param RRule $rule
80 *
81 * @return array
82 */
83 public function loadRRule(RRule $rule): array
84 {
85 $values = [];
86 $isMonthly = $rule->getFrequency() === RRule::MONTHLY;
87 if ($isMonthly && (! empty($rule->getByMonthDay()) || empty($rule->getByDay()))) {
88 $monthDays = $rule->getByMonthDay() ?? [];
89 foreach (range(1, $this->availableFields) as $value) {
90 $values["day$value"] = in_array((string) $value, $monthDays, true) ? 'y' : 'n';
91 }
92
93 $values['runsOn'] = MonthlyFields::RUNS_EACH;
94 } else {
95 $position = $rule->getBySetPosition();
96 $byDay = $rule->getByDay() ?? [];
97
98 if ($isMonthly) {
99 $values['runsOn'] = MonthlyFields::RUNS_ONTHE;
100 } else {
101 $months = $rule->getByMonth();
102 if (empty($months) && $rule->getStart()) {
103 $months[] = $rule->getStart()->format('m');
104 } elseif (empty($months)) {
105 $months[] = date('m');
106 }
107
108 $values['month'] = strtoupper($this->getMonthByNumber((int) $months[0]));
109 $values['runsOnThe'] = ! empty($byDay) ? 'y' : 'n';
110 }
111
112 if (count($byDay) == 1 && preg_match('/^(-?\d)(\w.*)$/', $byDay[0], $matches)) {
113 $values['ordinal'] = $this->getOrdinalString($matches[1]);
114 $values['day'] = $this->getWeekdayName($matches[2]);
115 } elseif (! empty($byDay)) {
116 $values['ordinal'] = $this->getOrdinalString(current($position));
117 switch (count($byDay)) {
118 case MonthlyFields::WEEK_DAYS:
119 $values['day'] = static::$everyDay;
120
121 break;
122 case MonthlyFields::WEEK_DAYS - 2:
123 $values['day'] = static::$everyWeekday;
124
125 break;
126 case 1:
127 $values['day'] = current($byDay);
128
129 break;
130 case 2:
131 $byDay = array_flip($byDay);
132 if (isset($byDay['SA']) && isset($byDay['SU'])) {
133 $values['day'] = static::$everyWeekend;
134 }
135 }
136 }
137 }
138
139 return $values;
140 }
141
142 /**
143 * Transform the given expression part into a valid week day string representation
144 *
145 * @param string $day
146 *
147 * @return string
148 */
149 public function getWeekdayName(string $day): string
150 {
151 // Not transformation is needed when the given day is part of the valid weekdays
152 if (isset($this->regulars[strtoupper($day)])) {
153 return $day;
154 }
155
156 try {
157 // Try to figure it out using date time before raising an error
158 $datetime = new DateTime('Sunday');
159 $datetime->add(new DateInterval("P$day" . 'D'));
160
161 return $datetime->format('D');
162 } catch (Exception $_) {
163 throw new InvalidArgumentException(sprintf('Invalid weekday provided: %s', $day));
164 }
165 }
166
167 /**
168 * Transform the given integer enums into something like first,second...
169 *
170 * @param string $ordinal
171 *
172 * @return string
173 */
174 public function getOrdinalString(string $ordinal): string
175 {
176 switch ($ordinal) {
177 case '1':
178 return static::$first;
179 case '2':
180 return static::$second;
181 case '3':
182 return static::$third;
183 case '4':
184 return static::$fourth;
185 case '5':
186 return static::$fifth;
187 case '-1':
188 return static::$last;
189 default:
190 throw new InvalidArgumentException(
191 sprintf('Invalid ordinal string representation provided: %s', $ordinal)
192 );
193 }
194 }
195
196 /**
197 * Get the string representation of the given ordinal to an integer
198 *
199 * This transforms the given ordinal such as (first, second...) into its respective
200 * integral representation. At the moment only (1..5 + the non-standard "last") options
201 * are supported. So if this method returns the character "-1", is meant the last option.
202 *
203 * @param string $ordinal
204 *
205 * @return int
206 */
207 public function getOrdinalAsInteger(string $ordinal): int
208 {
209 switch ($ordinal) {
210 case static::$first:
211 return 1;
212 case static::$second:
213 return 2;
214 case static::$third:
215 return 3;
216 case static::$fourth:
217 return 4;
218 case static::$fifth:
219 return 5;
220 case static::$last:
221 return -1;
222 default:
223 throw new InvalidArgumentException(sprintf('Invalid enumerator provided: %s', $ordinal));
224 }
225 }
226
227 /**
228 * Get a short textual representation of the given month
229 *
230 * @param int $month
231 *
232 * @return string
233 */
234 public function getMonthByNumber(int $month): string
235 {
236 $time = DateTime::createFromFormat('!m', $month);
237 if ($time) {
238 return $time->format('M');
239 }
240
241 throw new InvalidArgumentException(sprintf('Invalid month number provided: %d', $month));
242 }
243 }