Debian Codegraph @

vendor/ipl/html/src/Attributes.php

raw
1 <?php
2
3 namespace ipl\Html;
4
5 use ArrayAccess;
6 use ArrayIterator;
7 use InvalidArgumentException;
8 use IteratorAggregate;
9 use Traversable;
10
11 use function ipl\Stdlib\get_php_type;
12
13 /**
14 * HTML attributes
15 *
16 * HTML attributes provide additional information about HTML elements, that configure the elements or adjust their
17 * behavior in various ways.
18 *
19 * Attributes usually come in name-value pairs and are rendered as name="value".
20 *
21 * @phpstan-import-type AttributeValue from Attribute
22 * @phpstan-type AttributesType array<string, AttributeValue>
23 */
24 class Attributes implements ArrayAccess, IteratorAggregate
25 {
26 /** @var Attribute[] */
27 protected $attributes = [];
28
29 /** @var callable[] */
30 protected $callbacks = [];
31
32 /** @var string */
33 protected $prefix = '';
34
35 /** @var callable[] */
36 protected $setterCallbacks = [];
37
38 /**
39 * Create new HTML attributes
40 *
41 * @param ?AttributesType $attributes
42 */
43 public function __construct(?array $attributes = null)
44 {
45 if (empty($attributes)) {
46 return;
47 }
48
49 foreach ($attributes as $key => $value) {
50 if ($value instanceof Attribute) {
51 $this->addAttribute($value);
52 } elseif (is_string($key)) {
53 $this->add($key, $value);
54 } elseif (is_array($value) && count($value) === 2) {
55 $this->add(array_shift($value), array_shift($value));
56 }
57 }
58 }
59
60 /**
61 * Create new HTML attributes
62 *
63 * @param ?AttributesType $attributes
64 *
65 * @return static
66 */
67 public static function create(?array $attributes = null)
68 {
69 return new static($attributes);
70 }
71
72 /**
73 * Ensure that the given attributes of mixed type are converted to an instance of attributes
74 *
75 * The conversion procedure is as follows:
76 *
77 * If the given attributes is already an instance of Attributes, returns the very same element.
78 * If the attributes are given as an array of attribute name-value pairs, they are used to
79 * construct and return a new Attributes instance.
80 * If the attributes are null, an empty new instance of Attributes is returned.
81 *
82 * @param AttributesType|static|null $attributes
83 *
84 * @return static
85 *
86 * @throws InvalidArgumentException In case the given attributes are of an unsupported type
87 */
88 public static function wantAttributes($attributes)
89 {
90 if ($attributes instanceof self) {
91 return $attributes;
92 }
93
94 if (is_array($attributes)) {
95 return new static($attributes);
96 }
97
98 if ($attributes === null) {
99 return new static();
100 }
101
102 throw new InvalidArgumentException(sprintf(
103 'Attributes instance, array or null expected. Got %s instead.',
104 get_php_type($attributes)
105 ));
106 }
107
108 /**
109 * Get the collection of attributes as array
110 *
111 * @return Attribute[]
112 */
113 public function getAttributes()
114 {
115 return $this->attributes;
116 }
117
118 /**
119 * Merge the given attributes
120 *
121 * @param Attributes $attributes
122 *
123 * @return $this
124 */
125 public function merge(Attributes $attributes)
126 {
127 foreach ($attributes as $attribute) {
128 $this->addAttribute($attribute);
129 }
130
131 foreach ($attributes->callbacks as $name => $getter) {
132 $setter = null;
133 if (isset($attributes->setterCallbacks[$name])) {
134 $setter = $attributes->setterCallbacks[$name];
135 }
136
137 $this->registerAttributeCallback($name, $getter, $setter);
138 }
139
140 return $this;
141 }
142
143 /**
144 * Return true if the attribute with the given name exists, false otherwise
145 *
146 * @param string $name
147 *
148 * @return bool
149 */
150 public function has($name)
151 {
152 return array_key_exists($name, $this->attributes);
153 }
154
155 /**
156 * Get the attribute with the given name
157 *
158 * If the attribute does not yet exist, it is automatically created and registered to this Attributes instance.
159 *
160 * @param string $name
161 *
162 * @return Attribute
163 *
164 * @throws InvalidArgumentException If the attribute does not yet exist and its name contains special characters
165 */
166 public function get($name)
167 {
168 if (! $this->has($name)) {
169 $this->attributes[$name] = Attribute::createEmpty($name);
170 }
171
172 return $this->attributes[$name];
173 }
174
175 /**
176 * Set the given attribute(s)
177 *
178 * If the attribute with the given name already exists, it gets overridden.
179 *
180 * @param string|AttributesType|Attribute|self $attribute The attribute(s) to add
181 * @param AttributeValue $value The value of the attribute
182 *
183 * @return $this
184 *
185 * @throws InvalidArgumentException If the attribute name contains special characters
186 */
187 public function set($attribute, $value = null)
188 {
189 if ($attribute instanceof self) {
190 foreach ($attribute as $a) {
191 $this->setAttribute($a);
192 }
193
194 return $this;
195 }
196
197 if ($attribute instanceof Attribute) {
198 $this->setAttribute($attribute);
199
200 return $this;
201 }
202
203 if (is_array($attribute)) {
204 foreach ($attribute as $name => $value) {
205 $this->set($name, $value);
206 }
207
208 return $this;
209 }
210
211 if (array_key_exists($attribute, $this->setterCallbacks)) {
212 $callback = $this->setterCallbacks[$attribute];
213
214 $callback($value);
215
216 return $this;
217 }
218
219 $this->attributes[$attribute] = Attribute::create($attribute, $value);
220
221 return $this;
222 }
223
224 /**
225 * Add the given attribute(s)
226 *
227 * If an attribute with the same name already exists, the attribute's value will be added to the current value of
228 * the attribute.
229 *
230 * @param string|AttributesType|Attribute|self $attribute The attribute(s) to add
231 * @param AttributeValue $value The value of the attribute
232 *
233 * @return $this
234 *
235 * @throws InvalidArgumentException If the attribute does not yet exist and its name contains special characters
236 */
237 public function add($attribute, $value = null)
238 {
239 if ($attribute === null) {
240 return $this;
241 }
242
243 if ($attribute instanceof self) {
244 foreach ($attribute as $attr) {
245 $this->add($attr);
246 }
247
248 return $this;
249 }
250
251 if (is_array($attribute)) {
252 // TODO: Handle if $attribute = [new Attribute('class', 'bar')]
253 foreach ($attribute as $name => $value) {
254 $this->add($name, $value);
255 }
256
257 return $this;
258 }
259
260 if ($attribute instanceof Attribute) {
261 $this->addAttribute($attribute);
262
263 return $this;
264 }
265
266 if (array_key_exists($attribute, $this->setterCallbacks)) {
267 $callback = $this->setterCallbacks[$attribute];
268
269 $callback($value);
270
271 return $this;
272 }
273
274 if (! array_key_exists($attribute, $this->attributes)) {
275 $this->attributes[$attribute] = Attribute::create($attribute, $value);
276 } else {
277 $this->attributes[$attribute]->addValue($value);
278 }
279
280 return $this;
281 }
282
283 /**
284 * Remove the attribute with the given name or remove the given value from the attribute
285 *
286 * @param string $name The name of the attribute
287 * @param AttributeValue $value The value to remove if specified
288 *
289 * @return ?Attribute The removed or changed attribute, if any, otherwise null
290 */
291 public function remove($name, $value = null): ?Attribute
292 {
293 if (! $this->has($name)) {
294 return null;
295 }
296
297 $attribute = $this->attributes[$name];
298
299 if ($value === null) {
300 unset($this->attributes[$name]);
301 } else {
302 $attribute->removeValue($value);
303 }
304
305 return $attribute;
306 }
307
308 /**
309 * Set the specified attribute
310 *
311 * @param Attribute $attribute
312 *
313 * @return $this
314 */
315 public function setAttribute(Attribute $attribute)
316 {
317 $this->attributes[$attribute->getName()] = $attribute;
318
319 return $this;
320 }
321
322 /**
323 * Add the specified attribute
324 *
325 * If an attribute with the same name already exists, the given attribute's value
326 * will be added to the current value of the attribute.
327 *
328 * @param Attribute $attribute
329 *
330 * @return $this
331 */
332 public function addAttribute(Attribute $attribute)
333 {
334 $name = $attribute->getName();
335
336 if ($this->has($name)) {
337 $this->attributes[$name]->addValue($attribute->getValue());
338 } else {
339 $this->attributes[$name] = $attribute;
340 }
341
342 return $this;
343 }
344
345 /**
346 * Get the attributes name prefix
347 *
348 * @return string|null
349 */
350 public function getPrefix()
351 {
352 return $this->prefix;
353 }
354
355 /**
356 * Set the attributes name prefix
357 *
358 * @param string $prefix
359 *
360 * @return $this
361 */
362 public function setPrefix($prefix)
363 {
364 $this->prefix = $prefix;
365
366 return $this;
367 }
368
369 /**
370 * Register callback for an attribute
371 *
372 * @param string $name Name of the attribute to register the callback for
373 * @param ?callable $callback Callback to call when retrieving the attribute
374 * @param ?callable $setterCallback Callback to call when setting the attribute
375 *
376 * @return $this
377 */
378 public function registerAttributeCallback(string $name, ?callable $callback, ?callable $setterCallback = null): self
379 {
380 if ($callback !== null) {
381 $this->callbacks[$name] = $callback;
382 }
383
384 if ($setterCallback !== null) {
385 $this->setterCallbacks[$name] = $setterCallback;
386 }
387
388 return $this;
389 }
390
391 /**
392 * Render attributes to HTML
393 *
394 * If the value of an attribute is of type boolean, it will be rendered as
395 * {@link http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes boolean attribute}.
396 *
397 * If the value of an attribute is null, it will be skipped.
398 *
399 * HTML-escaping of the attributes' values takes place automatically using {@link Attribute::escapeValue()}.
400 *
401 * @return string
402 *
403 * @throws InvalidArgumentException If the result of a callback is invalid
404 */
405 public function render()
406 {
407 $attributes = $this->attributes;
408 foreach ($this->callbacks as $name => $callback) {
409 $attribute = call_user_func($callback);
410 if ($attribute instanceof Attribute) {
411 if ($attribute->isEmpty()) {
412 continue;
413 }
414 } elseif ($attribute === null) {
415 continue;
416 } elseif (is_scalar($attribute)) {
417 $attribute = Attribute::create($name, $attribute);
418 } else {
419 throw new InvalidArgumentException(sprintf(
420 'A registered attribute callback must return a scalar, null'
421 . ' or an Attribute, got a %s',
422 get_php_type($attribute)
423 ));
424 }
425
426 $name = $attribute->getName();
427 if (isset($attributes[$name])) {
428 $attributes[$name] = clone $attributes[$name];
429 $attributes[$name]->addValue($attribute->getValue());
430 } else {
431 $attributes[$name] = $attribute;
432 }
433 }
434
435 $parts = [];
436 foreach ($attributes as $attribute) {
437 if ($attribute->isEmpty()) {
438 continue;
439 }
440
441 $parts[] = $attribute->render();
442 }
443
444 if (empty($parts)) {
445 return '';
446 }
447
448 $separator = ' ' . $this->getPrefix();
449
450 return $separator . implode($separator, $parts);
451 }
452
453 /**
454 * Get whether the attribute with the given name exists
455 *
456 * @param string $name Name of the attribute
457 *
458 * @return bool
459 */
460 public function offsetExists($name): bool
461 {
462 return $this->has($name);
463 }
464
465 /**
466 * Get the attribute with the given name
467 *
468 * If the attribute does not yet exist, it is automatically created and registered to this Attributes instance.
469 *
470 * @param string $name Name of the attribute
471 *
472 * @return Attribute
473 *
474 * @throws InvalidArgumentException If the attribute does not yet exist and its name contains special characters
475 */
476 public function offsetGet($name): Attribute
477 {
478 return $this->get($name);
479 }
480
481 /**
482 * Set the given attribute
483 *
484 * If the attribute with the given name already exists, it gets overridden.
485 *
486 * @param string $name Name of the attribute
487 * @param AttributeValue $value Value of the attribute
488 *
489 * @throws InvalidArgumentException If the attribute name contains special characters
490 */
491 public function offsetSet($name, $value): void
492 {
493 $this->set($name, $value);
494 }
495
496 /**
497 * Remove the attribute with the given name
498 *
499 * @param string $name Name of the attribute
500 */
501 public function offsetUnset($name): void
502 {
503 $this->remove($name);
504 }
505
506 /**
507 * Get an iterator for traversing the attributes
508 *
509 * @return Attribute[]|ArrayIterator
510 */
511 public function getIterator(): Traversable
512 {
513 return new ArrayIterator($this->attributes);
514 }
515
516 public function __clone()
517 {
518 foreach ($this->attributes as &$attribute) {
519 $attribute = clone $attribute;
520 }
521 }
522 }