3 namespace dokuwiki\Form
;
8 * The basic building block of a form
10 * @package dokuwiki\Form
12 abstract class Element
15 * @var array the attributes of this element
17 protected $attributes = [];
20 * @var string The type of this element
25 * @param string $type The type of this element
26 * @param array $attributes
28 public function __construct($type, $attributes = [])
31 $this->attributes
= $attributes;
35 * Type of this element
39 public function getType()
45 * Gets or sets an attribute
47 * When no $value is given, the current content of the attribute is returned.
48 * An empty string is returned for unset attributes.
50 * When a $value is given, the content is set to that value and the Element
51 * itself is returned for easy chaining
53 * @param string $name Name of the attribute to access
54 * @param null|string $value New value to set
55 * @return string|$this
57 public function attr($name, $value = null)
60 if ($value !== null) {
61 $this->attributes
[$name] = $value;
66 if (isset($this->attributes
[$name])) {
67 return $this->attributes
[$name];
74 * Removes the given attribute if it exists
79 public function rmattr($name)
81 if (isset($this->attributes
[$name])) {
82 unset($this->attributes
[$name]);
88 * Gets or adds a all given attributes at once
90 * @param array|null $attributes
93 public function attrs($attributes = null)
97 foreach ((array) $attributes as $key => $val) {
98 $this->attr($key, $val);
103 return $this->attributes
;
107 * Adds a class to the class attribute
109 * This is the preferred method of setting the element's class
111 * @param string $class the new class to add
114 public function addClass($class)
116 $classes = explode(' ', $this->attr('class'));
118 $classes = array_unique($classes);
119 $classes = array_filter($classes);
120 $this->attr('class', implode(' ', $classes));
125 * Get or set the element's ID
127 * This is the preferred way of setting the element's ID
129 * @param null|string $id
130 * @return string|$this
132 public function id($id = null)
134 if (strpos($id, '__') === false) {
135 throw new \
InvalidArgumentException('IDs in DokuWiki have to contain two subsequent underscores');
138 return $this->attr('id', $id);
142 * Get or set the element's value
144 * This is the preferred way of setting the element's value
146 * @param null|string $value
147 * @return string|$this
149 public function val($value = null)
151 return $this->attr('value', $value);
155 * The HTML representation of this element
159 abstract public function toHTML();