1<?php
2
3namespace dokuwiki\plugin\struct\types;
4
5class Checkbox extends AbstractBaseType
6{
7    protected $config = ['values' => 'one, two, three'];
8
9    /**
10     * Creates the options array
11     *
12     * @return array
13     */
14    protected function getOptions()
15    {
16        $options = explode(',', $this->config['values']);
17        $options = array_map('trim', $options);
18        $options = array_filter($options);
19        return $options;
20    }
21
22    /**
23     * A single checkbox, additional values are ignored
24     *
25     * @param string $name
26     * @param string $rawvalue
27     * @param string $htmlID
28     *
29     * @return string
30     */
31    public function valueEditor($name, $rawvalue, $htmlID)
32    {
33        $options = $this->getOptions();
34        $opt = array_shift($options);
35
36        if ($rawvalue == $opt) {
37            $checked = 'checked';
38        } else {
39            $checked = '';
40        }
41        $opt = hsc($opt);
42        $params = [
43            'name' => $name,
44            'value' => $opt,
45            'class' => 'struct_' . strtolower($this->getClass()),
46            'type' => 'checkbox',
47            'id' => $htmlID,
48            'checked' => $checked
49        ];
50        $attributes = buildAttributes($params, true);
51        return "<label><input $attributes>&nbsp;$opt</label>";
52    }
53
54    /**
55     * Multiple checkboxes
56     *
57     * @param string $name
58     * @param \string[] $rawvalues
59     * @param string $htmlID
60     *
61     * @return string
62     */
63    public function multiValueEditor($name, $rawvalues, $htmlID)
64    {
65        $class = 'struct_' . strtolower($this->getClass());
66
67        $html = '';
68        foreach ($this->getOptions() as $opt) {
69            if (in_array($opt, $rawvalues)) {
70                $checked = 'checked';
71            } else {
72                $checked = '';
73            }
74
75            $params = [
76                'name' => $name . '[]',
77                'value' => $opt,
78                'class' => $class,
79                'type' => 'checkbox',
80                'id' => $htmlID,
81                'checked' => $checked
82            ];
83            $attributes = buildAttributes($params, true);
84            $htmlID = '';
85
86            $opt = hsc($opt);
87            $html .= "<label><input $attributes>&nbsp;$opt</label>";
88        }
89        return $html;
90    }
91}
92