comparison core/lib/Drupal/Core/Template/AttributeArray.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Core\Template;
4
5 use Drupal\Component\Utility\Html;
6
7 /**
8 * A class that defines a type of Attribute that can be added to as an array.
9 *
10 * To use with Attribute, the array must be specified.
11 * Correct:
12 * @code
13 * $attributes = new Attribute();
14 * $attributes['class'] = array();
15 * $attributes['class'][] = 'cat';
16 * @endcode
17 * Incorrect:
18 * @code
19 * $attributes = new Attribute();
20 * $attributes['class'][] = 'cat';
21 * @endcode
22 *
23 * @see \Drupal\Core\Template\Attribute
24 */
25 class AttributeArray extends AttributeValueBase implements \ArrayAccess, \IteratorAggregate {
26
27 /**
28 * Ensures empty array as a result of array_filter will not print '$name=""'.
29 *
30 * @see \Drupal\Core\Template\AttributeArray::__toString()
31 * @see \Drupal\Core\Template\AttributeValueBase::render()
32 */
33 const RENDER_EMPTY_ATTRIBUTE = FALSE;
34
35 /**
36 * {@inheritdoc}
37 */
38 public function offsetGet($offset) {
39 return $this->value[$offset];
40 }
41
42 /**
43 * {@inheritdoc}
44 */
45 public function offsetSet($offset, $value) {
46 if (isset($offset)) {
47 $this->value[$offset] = $value;
48 }
49 else {
50 $this->value[] = $value;
51 }
52 }
53
54 /**
55 * {@inheritdoc}
56 */
57 public function offsetUnset($offset) {
58 unset($this->value[$offset]);
59 }
60
61 /**
62 * {@inheritdoc}
63 */
64 public function offsetExists($offset) {
65 return isset($this->value[$offset]);
66 }
67
68 /**
69 * Implements the magic __toString() method.
70 */
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));
75 }
76
77 /**
78 * {@inheritdoc}
79 */
80 public function getIterator() {
81 return new \ArrayIterator($this->value);
82 }
83
84 /**
85 * Exchange the array for another one.
86 *
87 * @see ArrayObject::exchangeArray
88 *
89 * @param array $input
90 * The array input to replace the internal value.
91 *
92 * @return array
93 * The old array value.
94 */
95 public function exchangeArray($input) {
96 $old = $this->value;
97 $this->value = $input;
98 return $old;
99 }
100
101 }