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

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children af1871eacc83
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Core\Template;
4
5 use Drupal\Component\Render\PlainTextOutput;
6 use Drupal\Component\Render\MarkupInterface;
7
8 /**
9 * Collects, sanitizes, and renders HTML attributes.
10 *
11 * To use, optionally pass in an associative array of defined attributes, or
12 * add attributes using array syntax. For example:
13 * @code
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">
19 * @endcode
20 *
21 * $attributes always prints out all the attributes. For example:
22 * @code
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">
28 * @endcode
29 *
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:
33 * @code
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"> #}
36 * @endcode
37 *
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:
43 * @code
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(&quot;xss&quot;);">
49 * @endcode
50 *
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:
54 * @code
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 &lt;em&gt; tag">
59 * @endcode
60 *
61 * @see \Drupal\Component\Utility\Html::escape()
62 * @see \Drupal\Component\Render\PlainTextOutput::renderFromHtml()
63 * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
64 */
65 class Attribute implements \ArrayAccess, \IteratorAggregate, MarkupInterface {
66
67 /**
68 * Stores the attribute data.
69 *
70 * @var \Drupal\Core\Template\AttributeValueBase[]
71 */
72 protected $storage = [];
73
74 /**
75 * Constructs a \Drupal\Core\Template\Attribute object.
76 *
77 * @param array $attributes
78 * An associative array of key-value pairs to be converted to attributes.
79 */
80 public function __construct($attributes = []) {
81 foreach ($attributes as $name => $value) {
82 $this->offsetSet($name, $value);
83 }
84 }
85
86 /**
87 * {@inheritdoc}
88 */
89 public function offsetGet($name) {
90 if (isset($this->storage[$name])) {
91 return $this->storage[$name];
92 }
93 }
94
95 /**
96 * {@inheritdoc}
97 */
98 public function offsetSet($name, $value) {
99 $this->storage[$name] = $this->createAttributeValue($name, $value);
100 }
101
102 /**
103 * Creates the different types of attribute values.
104 *
105 * @param string $name
106 * The attribute name.
107 * @param mixed $value
108 * The attribute value.
109 *
110 * @return \Drupal\Core\Template\AttributeValueBase
111 * An AttributeValueBase representation of the attribute's value.
112 */
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());
119 }
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];
125 }
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);
131 }
132 elseif (is_bool($value)) {
133 $value = new AttributeBoolean($name, $value);
134 }
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);
141 }
142 elseif (!is_object($value)) {
143 $value = new AttributeString($name, $value);
144 }
145 return $value;
146 }
147
148 /**
149 * {@inheritdoc}
150 */
151 public function offsetUnset($name) {
152 unset($this->storage[$name]);
153 }
154
155 /**
156 * {@inheritdoc}
157 */
158 public function offsetExists($name) {
159 return isset($this->storage[$name]);
160 }
161
162 /**
163 * Adds classes or merges them on to array of existing CSS classes.
164 *
165 * @param string|array ...
166 * CSS classes to add to the class attribute array.
167 *
168 * @return $this
169 */
170 public function addClass() {
171 $args = func_get_args();
172 if ($args) {
173 $classes = [];
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);
179 }
180
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);
186 }
187 else {
188 $this->offsetSet('class', $classes);
189 }
190 }
191
192 return $this;
193 }
194
195 /**
196 * Sets values for an attribute key.
197 *
198 * @param string $attribute
199 * Name of the attribute.
200 * @param string|array $value
201 * Value(s) to set for the given attribute key.
202 *
203 * @return $this
204 */
205 public function setAttribute($attribute, $value) {
206 $this->offsetSet($attribute, $value);
207
208 return $this;
209 }
210
211 /**
212 * Removes an attribute from an Attribute object.
213 *
214 * @param string|array ...
215 * Attributes to remove from the attribute array.
216 *
217 * @return $this
218 */
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]);
226 }
227 }
228 else {
229 unset($this->storage[$arg]);
230 }
231 }
232
233 return $this;
234 }
235
236 /**
237 * Removes argument values from array of existing CSS classes.
238 *
239 * @param string|array ...
240 * CSS classes to remove from the class attribute array.
241 *
242 * @return $this
243 */
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();
248 $classes = [];
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);
254 }
255
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);
260 }
261 return $this;
262 }
263
264 /**
265 * Checks if the class array has the given CSS class.
266 *
267 * @param string $class
268 * The CSS class to check for.
269 *
270 * @return bool
271 * Returns TRUE if the class exists, or FALSE otherwise.
272 */
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());
276 }
277 else {
278 return FALSE;
279 }
280 }
281
282 /**
283 * Implements the magic __toString() method.
284 */
285 public function __toString() {
286 $return = '';
287 /** @var \Drupal\Core\Template\AttributeValueBase $value */
288 foreach ($this->storage as $name => $value) {
289 $rendered = $value->render();
290 if ($rendered) {
291 $return .= ' ' . $rendered;
292 }
293 }
294 return $return;
295 }
296
297 /**
298 * Returns all storage elements as an array.
299 *
300 * @return array
301 * An associative array of attributes.
302 */
303 public function toArray() {
304 $return = [];
305 foreach ($this->storage as $name => $value) {
306 $return[$name] = $value->value();
307 }
308
309 return $return;
310 }
311
312 /**
313 * Implements the magic __clone() method.
314 */
315 public function __clone() {
316 foreach ($this->storage as $name => $value) {
317 $this->storage[$name] = clone $value;
318 }
319 }
320
321 /**
322 * {@inheritdoc}
323 */
324 public function getIterator() {
325 return new \ArrayIterator($this->storage);
326 }
327
328 /**
329 * Returns the whole array.
330 */
331 public function storage() {
332 return $this->storage;
333 }
334
335 /**
336 * Returns a representation of the object for use in JSON serialization.
337 *
338 * @return string
339 * The safe string content.
340 */
341 public function jsonSerialize() {
342 return (string) $this;
343 }
344
345 }