AttributeArray.php 1.76 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Definition of Drupal\Core\Template\AttributeArray.
 */

namespace Drupal\Core\Template;

10
use Drupal\Component\Utility\String;
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

/**
 * 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
 *  $attributes = new Attribute(array());
 *  $attributes['class'] = array();
 *  $attributes['class'][] = 'cat';
 * @endcode
 * Incorrect:
 * @code
 *  $attributes = new Attribute(array());
 *  $attributes['class'][] = 'cat';
 * @endcode
 *
 * @see Drupal\Core\Template\Attribute
 */
30
class AttributeArray extends AttributeValueBase implements \ArrayAccess, \IteratorAggregate {
31 32 33 34 35 36 37 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

  /**
   * 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() {
    $this->printed = TRUE;
70
    return implode(' ', array_map(array('Drupal\Component\Utility\String', 'checkPlain'), $this->value));
71 72 73 74 75 76
  }

  /**
   * Implements IteratorAggregate::getIterator().
   */
  public function getIterator() {
77
    return new \ArrayIterator($this->value);
78 79 80 81 82 83 84 85 86 87
  }

  /**
   * Returns the whole array.
   */
  public function value() {
    return $this->value;
  }

}