AttributeArray.php 1.72 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
<?php

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

namespace Drupal\Core\Template;

use ArrayAccess;
use IteratorAggregate;

/**
 * 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
 */
class AttributeArray extends AttributeValueBase implements ArrayAccess, IteratorAggregate {

  /**
   * 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;
    return implode(' ', array_map('check_plain', $this->value));
  }

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

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

}