XOOPS  2.6.0
Attributes.php
Go to the documentation of this file.
1 <?php
2 /*
3  You may not change or alter any portion of this comment or credits
4  of supporting developers from this source code or any supporting source code
5  which is considered copyrighted (c) material of the original comment or credit authors.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 */
11 
12 
13 namespace Xoops\Html;
14 
26 {
32  protected $attributes = array();
33 
42  public function setAttribute($name, $value = null)
43  {
44  // convert boolean to strings, so getAttribute can return boolean
45  // false for attributes that are not defined
46  $value = ($value===false) ? '0' : $value;
47  $value = ($value===true) ? '1' : $value;
48  $this->attributes[htmlspecialchars($name, ENT_QUOTES)] = $value;
49  }
50 
58  public function unsetAttribute($name)
59  {
60  unset($this->attributes[htmlspecialchars($name, ENT_QUOTES)]);
61  }
62 
70  public function setAttributes($values)
71  {
72  if (!empty($values)) {
73  foreach ($values as $name => $value) {
74  $this->setAttribute($name, $value);
75  }
76  }
77  }
78 
86  public function getAttribute($name)
87  {
88  $value = false;
89  $name = htmlspecialchars($name, ENT_QUOTES);
90  if (isset($this->attributes[$name])) {
91  $value = $this->attributes[$name];
92  }
93  return $value;
94  }
95 
103  public function hasAttribute($name)
104  {
105  $name = htmlspecialchars($name, ENT_QUOTES);
106  return array_key_exists($name, $this->attributes);
107  }
108 
117  public function addAttribute($name, $value)
118  {
119  if (is_scalar($value)) {
120  $value = explode(' ', (string) $value);
121  }
122  $name = htmlspecialchars($name, ENT_QUOTES);
123  if (false==$this->hasAttribute($name)) {
124  $this->attributes[$name] = array();
125  }
126  foreach ($value as $v) {
127  if (!in_array($v, $this->attributes[$name])) {
128  $this->attributes[$name][] = $v;
129  }
130  }
131  }
132 
138  public function renderAttributeString()
139  {
140  $rendered = '';
141  foreach ($this->attributes as $name => $value) {
142  if ($name == 'name'
143  && $this->hasAttribute('multiple')
144  && substr($value, -2) != '[]'
145  ) {
146  $value .= '[]';
147  }
148  if (is_array($value)) {
149  // arrays can be used for class attributes, space separated
150  $set = '="' . htmlspecialchars(implode(' ', $value), ENT_QUOTES) .'"';
151  } elseif ($value===null) {
152  // null indicates name only, like autofocus or readonly
153  $set = '';
154  } else {
155  $set = '="' . htmlspecialchars($value, ENT_QUOTES) .'"';
156  }
157  $rendered .= $name . $set . ' ';
158  }
159  return $rendered;
160  }
161 }
setAttribute($name, $value=null)
Definition: Attributes.php:42
addAttribute($name, $value)
Definition: Attributes.php:117