3 namespace Drupal\Core\Template;
5 use Drupal\Component\Utility\Html;
8 * A class that defines a type of Attribute that can be added to as an array.
10 * To use with Attribute, the array must be specified.
13 * $attributes = new Attribute();
14 * $attributes['class'] = array();
15 * $attributes['class'][] = 'cat';
19 * $attributes = new Attribute();
20 * $attributes['class'][] = 'cat';
23 * @see \Drupal\Core\Template\Attribute
25 class AttributeArray extends AttributeValueBase implements \ArrayAccess, \IteratorAggregate {
28 * Ensures empty array as a result of array_filter will not print '$name=""'.
30 * @see \Drupal\Core\Template\AttributeArray::__toString()
31 * @see \Drupal\Core\Template\AttributeValueBase::render()
33 const RENDER_EMPTY_ATTRIBUTE = FALSE;
38 public function offsetGet($offset) {
39 return $this->value[$offset];
45 public function offsetSet($offset, $value) {
47 $this->value[$offset] = $value;
50 $this->value[] = $value;
57 public function offsetUnset($offset) {
58 unset($this->value[$offset]);
64 public function offsetExists($offset) {
65 return isset($this->value[$offset]);
69 * Implements the magic __toString() method.
71 public function __toString() {
72 // Filter out any empty values before printing.
73 $this->value = array_unique(array_filter($this->value));
74 return Html::escape(implode(' ', $this->value));
80 public function getIterator() {
81 return new \ArrayIterator($this->value);
85 * Exchange the array for another one.
87 * @see ArrayObject::exchangeArray
90 * The array input to replace the internal value.
93 * The old array value.
95 public function exchangeArray($input) {
97 $this->value = $input;