AttributeArray.php 2.26 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Template\AttributeArray.
6 7 8 9 10 11 12 13 14 15
 */

namespace Drupal\Core\Template;

/**
 * A class that defines a type of Attribute that can be added to as an array.
 *
 * To use with Attribute, the array must be specified.
 * Correct:
 * @code
16
 *  $attributes = new Attribute();
17 18 19 20 21
 *  $attributes['class'] = array();
 *  $attributes['class'][] = 'cat';
 * @endcode
 * Incorrect:
 * @code
22
 *  $attributes = new Attribute();
23 24 25
 *  $attributes['class'][] = 'cat';
 * @endcode
 *
26
 * @see \Drupal\Core\Template\Attribute
27
 */
28
class AttributeArray extends AttributeValueBase implements \ArrayAccess, \IteratorAggregate {
29

30 31 32 33 34 35 36 37
  /**
   * Ensures empty array as a result of array_filter will not print '$name=""'.
   *
   * @see \Drupal\Core\Template\AttributeArray::__toString()
   * @see \Drupal\Core\Template\AttributeValueBase::render()
   */
  const RENDER_EMPTY_ATTRIBUTE = FALSE;

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
  /**
   * Implements ArrayAccess::offsetGet().
   */
  public function offsetGet($offset) {
    return $this->value[$offset];
  }

  /**
   * Implements ArrayAccess::offsetSet().
   */
  public function offsetSet($offset, $value) {
    if (isset($offset)) {
      $this->value[$offset] = $value;
    }
    else {
      $this->value[] = $value;
    }
  }

  /**
   * Implements ArrayAccess::offsetUnset().
   */
  public function offsetUnset($offset) {
    unset($this->value[$offset]);
  }

  /**
   * Implements ArrayAccess::offsetExists().
   */
  public function offsetExists($offset) {
    return isset($this->value[$offset]);
  }

  /**
   * Implements the magic __toString() method.
   */
  public function __toString() {
75
    // Filter out any empty values before printing.
76
    $this->value = array_unique(array_filter($this->value));
77
    return htmlspecialchars(implode(' ', $this->value), ENT_QUOTES, 'UTF-8');
78 79 80 81 82 83
  }

  /**
   * Implements IteratorAggregate::getIterator().
   */
  public function getIterator() {
84
    return new \ArrayIterator($this->value);
85 86
  }

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
  /**
   * Exchange the array for another one.
   *
   * @see ArrayObject::exchangeArray
   *
   * @param array $input
   *   The array input to replace the internal value.
   *
   * @return array
   *   The old array value.
   */
  public function exchangeArray($input) {
    $old = $this->value;
    $this->value = $input;
    return $old;
  }

104
}