ArrayElement.php 2.43 KB
Newer Older
1
2
3
4
5
6
7
8
<?php

/**
 * @file
 * Contains \Drupal\Core\Config\Schema\ArrayElement.
 */

namespace Drupal\Core\Config\Schema;
9
use Drupal\Core\TypedData\TraversableTypedDataInterface;
10
11
12
13

/**
 * Defines a generic configuration element that contains multiple properties.
 */
14
abstract class ArrayElement extends Element implements \IteratorAggregate, TraversableTypedDataInterface, \ArrayAccess, \Countable {
15
16

  /**
17
   * Parsed elements.
18
   */
19
  protected $elements;
20
21

  /**
22
   * Gets an array of contained elements.
23
   *
24
25
   * @return \Drupal\Core\TypedData\TypedDataInterface[]
   *   An array of elements contained in this element.
26
   */
27
28
29
30
31
32
  protected function getElements() {
    if (!isset($this->elements)) {
      $this->elements = $this->parse();
    }
    return $this->elements;
  }
33
34
35
36
37
38
39
40
41
42
43
44
45
46

  /**
   * Gets valid configuration data keys.
   *
   * @return array
   *   Array of valid configuration data keys.
   */
  protected function getAllKeys() {
    return is_array($this->value) ? array_keys($this->value) : array();
  }

  /**
   * Builds an array of contained elements.
   *
47
48
   * @return \Drupal\Core\TypedData\TypedDataInterface[]
   *   An array of elements contained in this element.
49
   */
50
  protected abstract function parse();
51
52

  /**
53
   * Implements TypedDataInterface::validate().
54
   */
55
56
57
58
  public function validate() {
    foreach ($this->getElements() as $element) {
      if (!$element->validate()) {
        return FALSE;
59
60
      }
    }
61
    return TRUE;
62
63
64
  }

  /**
65
   * Implements ArrayAccess::offsetExists().
66
   */
67
68
  public function offsetExists($offset) {
    return array_key_exists($offset, $this->getElements());
69
70
71
  }

  /**
72
   * Implements ArrayAccess::offsetGet().
73
   */
74
75
76
  public function offsetGet($offset) {
    $elements = $this->getElements();
    return $elements[$offset];
77
78
79
  }

  /**
80
   * Implements ArrayAccess::offsetSet().
81
   */
82
83
84
85
86
87
  public function offsetSet($offset, $value) {
    if ($value instanceof TypedDataInterface) {
      $value = $value->getValue();
    }
    $this->value[$offset] = $value;
    unset($this->elements);
88
89
90
  }

  /**
91
   * Implements ArrayAccess::offsetUnset().
92
   */
93
94
95
  public function offsetUnset($offset) {
    unset($this->value[$offset]);
    unset($this->elements);
96
97
98
  }

  /**
99
   * Implements Countable::count().
100
   */
101
102
  public function count() {
    return count($this->getElements());
103
104
105
106
107
108
  }

  /**
   * Implements IteratorAggregate::getIterator();
   */
  public function getIterator() {
109
    return new \ArrayIterator($this->getElements());
110
111
112
  }

}