xref: /dokuwiki/lib/plugins/config/core/Setting/SettingArray.php (revision 8c7c53b0321a3cd3116b8d3b2ad27863a38dece7)
1<?php
2
3namespace dokuwiki\plugin\config\core\Setting;
4
5/**
6 * Class setting_array
7 */
8class SettingArray extends Setting
9{
10
11    /**
12     * Create an array from a string
13     *
14     * @param string $string
15     * @return array
16     */
17    protected function fromString($string) {
18        $array = explode(',', $string);
19        $array = array_map('trim', $array);
20        $array = array_filter($array);
21        $array = array_unique($array);
22        return $array;
23    }
24
25    /**
26     * Create a string from an array
27     *
28     * @param array $array
29     * @return string
30     */
31    protected function fromArray($array) {
32        return implode(', ', (array) $array);
33    }
34
35    /**
36     * update setting with user provided value $input
37     * if value fails error check, save it
38     *
39     * @param string $input
40     * @return bool true if changed, false otherwise (incl. on error)
41     */
42    public function update($input) {
43        if(is_null($input)) return false;
44        if($this->isProtected()) return false;
45
46        $input = $this->fromString($input);
47
48        $value = is_null($this->local) ? $this->default : $this->local;
49        if($value == $input) return false;
50
51        foreach($input as $item) {
52            if($this->pattern && !preg_match($this->pattern, $item)) {
53                $this->error = true;
54                $this->input = $input;
55                return false;
56            }
57        }
58
59        $this->local = $input;
60        return true;
61    }
62
63    /** @inheritdoc */
64    public function html(\admin_plugin_config $plugin, $echo = false) {
65        $disable = '';
66
67        if ($this->isProtected()) {
68            $value = $this->protected;
69            $disable = 'disabled="disabled"';
70        } elseif ($echo && $this->error) {
71            $value = $this->input;
72        } else {
73            $value = is_null($this->local) ? $this->default : $this->local;
74        }
75
76        $key = htmlspecialchars($this->key);
77        $value = htmlspecialchars($this->fromArray($value));
78
79        $label = '<label for="config___' . $key . '">' . $this->prompt($plugin) . '</label>';
80        $input = '<input id="config___' . $key . '" name="config[' . $key .
81            ']" type="text" class="edit" value="' . $value . '" ' . $disable . '/>';
82        return [$label, $input];
83    }
84}
85