summaryrefslogtreecommitdiffstats
path: root/library/Reporting/Web/Forms/Decorator/CompatDecorator.php
blob: b2eb536c49e0cd3330696db9fbfcd5d9c4f549f4 (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
<?php
// Icinga Reporting | (c) 2021 Icinga GmbH | GPLv2

namespace Icinga\Module\Reporting\Web\Forms\Decorator;

use Icinga\Application\Version;
use ipl\Html\Attributes;
use ipl\Html\FormElement\CheckboxElement;
use ipl\Html\HtmlElement;

class CompatDecorator extends \ipl\Web\Compat\CompatDecorator
{
    protected function createCheckboxCompat(CheckboxElement $checkbox)
    {
        if (! $checkbox->getAttributes()->has('id')) {
            $checkbox->setAttribute('id', base64_encode(random_bytes(8)));
        }

        $checkbox->getAttributes()->add('class', 'sr-only');

        $classes = ['toggle-switch'];
        if ($checkbox->getAttributes()->get('disabled')->getValue()) {
            $classes[] = 'disabled';
        }

        return [
            $checkbox,
            new HtmlElement('label', Attributes::create([
                'class'         => $classes,
                'aria-hidden'   => 'true',
                'for'           => $checkbox->getAttributes()->get('id')->getValue()
            ]), new HtmlElement('span', Attributes::create(['class' => 'toggle-slider'])))
        ];
    }

    protected function assembleElementCompat()
    {
        if ($this->formElement instanceof CheckboxElement) {
            return $this->createCheckboxCompat($this->formElement);
        }

        return $this->formElement;
    }

    protected function assemble()
    {
        if (version_compare(Version::VERSION, '2.9.0', '>=')) {
            parent::assemble();
            return;
        }

        if ($this->formElement->hasBeenValidated() && ! $this->formElement->isValid()) {
            $this->getAttributes()->add('class', 'has-error');
        }

        $this->add(array_filter([
            $this->assembleLabel(),
            $this->assembleElementCompat(),
            $this->assembleDescription(),
            $this->assembleErrors()
        ]));
    }
}