3 namespace Drupal\Core\Template;
5 use Drupal\Component\Render\PlainTextOutput;
6 use Drupal\Component\Render\MarkupInterface;
9 * Collects, sanitizes, and renders HTML attributes.
11 * To use, optionally pass in an associative array of defined attributes, or
12 * add attributes using array syntax. For example:
14 * $attributes = new Attribute(array('id' => 'socks'));
15 * $attributes['class'] = array('black-cat', 'white-cat');
16 * $attributes['class'][] = 'black-white-cat';
17 * echo '<cat' . $attributes . '>';
18 * // Produces <cat id="socks" class="black-cat white-cat black-white-cat">
21 * $attributes always prints out all the attributes. For example:
23 * $attributes = new Attribute(array('id' => 'socks'));
24 * $attributes['class'] = array('black-cat', 'white-cat');
25 * $attributes['class'][] = 'black-white-cat';
26 * echo '<cat class="cat ' . $attributes['class'] . '"' . $attributes . '>';
27 * // Produces <cat class="cat black-cat white-cat black-white-cat" id="socks" class="cat black-cat white-cat black-white-cat">
30 * When printing out individual attributes to customize them within a Twig
31 * template, use the "without" filter to prevent attributes that have already
32 * been printed from being printed again. For example:
34 * <cat class="{{ attributes.class }} my-custom-class"{{ attributes|without('class') }}>
35 * {# Produces <cat class="cat black-cat white-cat black-white-cat my-custom-class" id="socks"> #}
38 * The attribute keys and values are automatically escaped for output with
39 * Html::escape(). No protocol filtering is applied, so when using user-entered
40 * input as a value for an attribute that expects an URI (href, src, ...),
41 * UrlHelper::stripDangerousProtocols() should be used to ensure dangerous
42 * protocols (such as 'javascript:') are removed. For example:
44 * $path = 'javascript:alert("xss");';
45 * $path = UrlHelper::stripDangerousProtocols($path);
46 * $attributes = new Attribute(array('href' => $path));
47 * echo '<a' . $attributes . '>';
48 * // Produces <a href="alert("xss");">
51 * The attribute values are considered plain text and are treated as such. If a
52 * safe HTML string is detected, it is converted to plain text with
53 * PlainTextOutput::renderFromHtml() before being escaped. For example:
55 * $value = t('Highlight the @tag tag', ['@tag' => '<em>']);
56 * $attributes = new Attribute(['value' => $value]);
57 * echo '<input' . $attributes . '>';
58 * // Produces <input value="Highlight the <em> tag">
61 * @see \Drupal\Component\Utility\Html::escape()
62 * @see \Drupal\Component\Render\PlainTextOutput::renderFromHtml()
63 * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
65 class Attribute implements \ArrayAccess, \IteratorAggregate, MarkupInterface {
68 * Stores the attribute data.
70 * @var \Drupal\Core\Template\AttributeValueBase[]
72 protected $storage = [];
75 * Constructs a \Drupal\Core\Template\Attribute object.
77 * @param array $attributes
78 * An associative array of key-value pairs to be converted to attributes.
80 public function __construct($attributes = []) {
81 foreach ($attributes as $name => $value) {
82 $this->offsetSet($name, $value);
89 public function offsetGet($name) {
90 if (isset($this->storage[$name])) {
91 return $this->storage[$name];
98 public function offsetSet($name, $value) {
99 $this->storage[$name] = $this->createAttributeValue($name, $value);
103 * Creates the different types of attribute values.
105 * @param string $name
106 * The attribute name.
107 * @param mixed $value
108 * The attribute value.
110 * @return \Drupal\Core\Template\AttributeValueBase
111 * An AttributeValueBase representation of the attribute's value.
113 protected function createAttributeValue($name, $value) {
114 // If the value is already an AttributeValueBase object,
115 // return a new instance of the same class, but with the new name.
116 if ($value instanceof AttributeValueBase) {
117 $class = get_class($value);
118 return new $class($name, $value->value());
120 // An array value or 'class' attribute name are forced to always be an
121 // AttributeArray value for consistency.
122 if ($name == 'class' && !is_array($value)) {
123 // Cast the value to string in case it implements MarkupInterface.
124 $value = [(string) $value];
126 if (is_array($value)) {
127 // Cast the value to an array if the value was passed in as a string.
128 // @todo Decide to fix all the broken instances of class as a string
129 // in core or cast them.
130 $value = new AttributeArray($name, $value);
132 elseif (is_bool($value)) {
133 $value = new AttributeBoolean($name, $value);
135 // As a development aid, we allow the value to be a safe string object.
136 elseif ($value instanceof MarkupInterface) {
137 // Attributes are not supposed to display HTML markup, so we just convert
138 // the value to plain text.
139 $value = PlainTextOutput::renderFromHtml($value);
140 $value = new AttributeString($name, $value);
142 elseif (!is_object($value)) {
143 $value = new AttributeString($name, $value);
151 public function offsetUnset($name) {
152 unset($this->storage[$name]);
158 public function offsetExists($name) {
159 return isset($this->storage[$name]);
163 * Adds classes or merges them on to array of existing CSS classes.
165 * @param string|array ...
166 * CSS classes to add to the class attribute array.
170 public function addClass() {
171 $args = func_get_args();
174 foreach ($args as $arg) {
175 // Merge the values passed in from the classes array.
176 // The argument is cast to an array to support comma separated single
177 // values or one or more array arguments.
178 $classes = array_merge($classes, (array) $arg);
181 // Merge if there are values, just add them otherwise.
182 if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
183 // Merge the values passed in from the class value array.
184 $classes = array_merge($this->storage['class']->value(), $classes);
185 $this->storage['class']->exchangeArray($classes);
188 $this->offsetSet('class', $classes);
196 * Sets values for an attribute key.
198 * @param string $attribute
199 * Name of the attribute.
200 * @param string|array $value
201 * Value(s) to set for the given attribute key.
205 public function setAttribute($attribute, $value) {
206 $this->offsetSet($attribute, $value);
212 * Removes an attribute from an Attribute object.
214 * @param string|array ...
215 * Attributes to remove from the attribute array.
219 public function removeAttribute() {
220 $args = func_get_args();
221 foreach ($args as $arg) {
222 // Support arrays or multiple arguments.
223 if (is_array($arg)) {
224 foreach ($arg as $value) {
225 unset($this->storage[$value]);
229 unset($this->storage[$arg]);
237 * Removes argument values from array of existing CSS classes.
239 * @param string|array ...
240 * CSS classes to remove from the class attribute array.
244 public function removeClass() {
245 // With no class attribute, there is no need to remove.
246 if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
247 $args = func_get_args();
249 foreach ($args as $arg) {
250 // Merge the values passed in from the classes array.
251 // The argument is cast to an array to support comma separated single
252 // values or one or more array arguments.
253 $classes = array_merge($classes, (array) $arg);
256 // Remove the values passed in from the value array. Use array_values() to
257 // ensure that the array index remains sequential.
258 $classes = array_values(array_diff($this->storage['class']->value(), $classes));
259 $this->storage['class']->exchangeArray($classes);
265 * Checks if the class array has the given CSS class.
267 * @param string $class
268 * The CSS class to check for.
271 * Returns TRUE if the class exists, or FALSE otherwise.
273 public function hasClass($class) {
274 if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
275 return in_array($class, $this->storage['class']->value());
283 * Implements the magic __toString() method.
285 public function __toString() {
287 /** @var \Drupal\Core\Template\AttributeValueBase $value */
288 foreach ($this->storage as $name => $value) {
289 $rendered = $value->render();
291 $return .= ' ' . $rendered;
298 * Returns all storage elements as an array.
301 * An associative array of attributes.
303 public function toArray() {
305 foreach ($this->storage as $name => $value) {
306 $return[$name] = $value->value();
313 * Implements the magic __clone() method.
315 public function __clone() {
316 foreach ($this->storage as $name => $value) {
317 $this->storage[$name] = clone $value;
324 public function getIterator() {
325 return new \ArrayIterator($this->storage);
329 * Returns the whole array.
331 public function storage() {
332 return $this->storage;
336 * Returns a representation of the object for use in JSON serialization.
339 * The safe string content.
341 public function jsonSerialize() {
342 return (string) $this;