AttributeArray.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Drupal\Core\Template;
  3. use Drupal\Component\Utility\Html;
  4. /**
  5. * A class that defines a type of Attribute that can be added to as an array.
  6. *
  7. * To use with Attribute, the array must be specified.
  8. * Correct:
  9. * @code
  10. * $attributes = new Attribute();
  11. * $attributes['class'] = array();
  12. * $attributes['class'][] = 'cat';
  13. * @endcode
  14. * Incorrect:
  15. * @code
  16. * $attributes = new Attribute();
  17. * $attributes['class'][] = 'cat';
  18. * @endcode
  19. *
  20. * @see \Drupal\Core\Template\Attribute
  21. */
  22. class AttributeArray extends AttributeValueBase implements \ArrayAccess, \IteratorAggregate {
  23. /**
  24. * Ensures empty array as a result of array_filter will not print '$name=""'.
  25. *
  26. * @see \Drupal\Core\Template\AttributeArray::__toString()
  27. * @see \Drupal\Core\Template\AttributeValueBase::render()
  28. */
  29. const RENDER_EMPTY_ATTRIBUTE = FALSE;
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function offsetGet($offset) {
  34. return $this->value[$offset];
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function offsetSet($offset, $value) {
  40. if (isset($offset)) {
  41. $this->value[$offset] = $value;
  42. }
  43. else {
  44. $this->value[] = $value;
  45. }
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function offsetUnset($offset) {
  51. unset($this->value[$offset]);
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function offsetExists($offset) {
  57. return isset($this->value[$offset]);
  58. }
  59. /**
  60. * Implements the magic __toString() method.
  61. */
  62. public function __toString() {
  63. // Filter out any empty values before printing.
  64. $this->value = array_unique(array_filter($this->value));
  65. return Html::escape(implode(' ', $this->value));
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function getIterator() {
  71. return new \ArrayIterator($this->value);
  72. }
  73. /**
  74. * Exchange the array for another one.
  75. *
  76. * @see ArrayObject::exchangeArray
  77. *
  78. * @param array $input
  79. * The array input to replace the internal value.
  80. *
  81. * @return array
  82. * The old array value.
  83. */
  84. public function exchangeArray($input) {
  85. $old = $this->value;
  86. $this->value = $input;
  87. return $old;
  88. }
  89. }