Debian Codegraph @

vendor/ipl/web/src/FormElement/ScheduleElement/Recurrence.php

raw
1 <?php
2
3 namespace ipl\Web\FormElement\ScheduleElement;
4
5 use DateTime;
6 use ipl\Html\Attributes;
7 use ipl\Html\FormElement\BaseFormElement;
8 use ipl\Html\HtmlElement;
9 use ipl\Html\Text;
10 use ipl\I18n\Translation;
11 use ipl\Scheduler\Contract\Frequency;
12 use ipl\Scheduler\RRule;
13
14 class Recurrence extends BaseFormElement
15 {
16 use Translation;
17
18 protected $tag = 'div';
19
20 protected $defaultAttributes = ['class' => 'schedule-recurrences'];
21
22 /** @var callable A callable that generates a frequency instance */
23 protected $frequencyCallback;
24
25 /** @var callable A validation callback for the schedule element */
26 protected $validateCallback;
27
28 /**
29 * Set a validation callback that will be called when assembling this element
30 *
31 * @param callable $callback
32 *
33 * @return $this
34 */
35 public function setValid(callable $callback): self
36 {
37 $this->validateCallback = $callback;
38
39 return $this;
40 }
41
42 /**
43 * Set a callback that generates an {@see Frequency} instance
44 *
45 * @param callable $callback
46 *
47 * @return $this
48 */
49 public function setFrequency(callable $callback): self
50 {
51 $this->frequencyCallback = $callback;
52
53 return $this;
54 }
55
56 protected function assemble()
57 {
58 list($isValid, $reason) = ($this->validateCallback)();
59 if (! $isValid) {
60 // Render why we can't generate the recurrences
61 $this->addHtml(Text::create($reason));
62
63 return;
64 }
65
66 /** @var RRule $frequency */
67 $frequency = ($this->frequencyCallback)();
68 $recurrences = $frequency->getNextRecurrences(new DateTime(), 3);
69 if (! $recurrences->valid()) {
70 // Such a situation can be caused by setting an invalid end time
71 $this->addHtml(HtmlElement::create('p', null, Text::create($this->translate('Never'))));
72
73 return;
74 }
75
76 foreach ($recurrences as $recurrence) {
77 $this->addHtml(HtmlElement::create('p', null, $recurrence->format($this->translate('D, Y/m/d, H:i:s'))));
78 }
79 }
80
81 protected function registerAttributeCallbacks(Attributes $attributes)
82 {
83 parent::registerAttributeCallbacks($attributes);
84
85 $attributes
86 ->registerAttributeCallback('frequency', null, [$this, 'setFrequency'])
87 ->registerAttributeCallback('validate', null, [$this, 'setValid']);
88 }
89 }