1: <?php
2:
3: namespace PHPixie\ORM\Data\Types\Document\Node;
4:
5: class ArrayNode extends \PHPixie\ORM\Data\Types\Document\Node implements \ArrayAccess, \Countable, \IteratorAggregate
6: {
7: protected $currentArray;
8:
9: public function __construct($documentBuilder, $array)
10: {
11: parent::__construct($documentBuilder);
12: $this->currentArray = array();
13: foreach($array as $value)
14: $this->currentArray[] = $this->convertValue($value);
15: }
16:
17: public function offsetExists($key)
18: {
19: return array_key_exists($key, $this->currentArray);
20: }
21:
22: public function offsetGet($key)
23: {
24: if (!$this->offsetExists($key))
25: throw new \PHPixie\ORM\Exception\Model("Key '$key' doesn't exist");
26: return $this->currentArray[$key];
27: }
28:
29: public function offsetSet($key, $value)
30: {
31: if($key > $this->count()) {
32: throw new \PHPixie\ORM\Exception\Data("Document arrays may not have gaps. Key $key is larger than array count {$this->count()}.");
33: }
34: $this->appendToCurrent($this->convertValue($value), $key);
35: }
36:
37: public function offsetUnset($key)
38: {
39: array_splice($this->currentArray, $key, 1);
40: }
41:
42: public function count()
43: {
44: return count($this->currentArray);
45: }
46:
47: public function getIterator()
48: {
49: return $this->documentBuilder->arrayIterator($this);
50: }
51:
52: public function clear()
53: {
54: $this->currentArray = array();
55: }
56:
57: public function data()
58: {
59: $current = array();
60: foreach($this->currentArray as $key => $value)
61: $current[$key] = $this->convertNode($value);
62:
63: return $current;
64: }
65:
66: public function append($value = null)
67: {
68: $this->appendToCurrent($this->convertValue($value));
69: return $this;
70: }
71:
72: public function last()
73: {
74: return $this->currentArray[$this->count()-1];
75: }
76:
77: public function appendArray($data = array(), $key = null)
78: {
79: return $this->appendToCurrent($this->documentBuilder->arrayNode($data), $key);
80: }
81:
82: public function appendDocument($data = null, $key = null)
83: {
84: return $this->appendToCurrent($this->documentBuilder->document($data), $key);
85: }
86:
87: protected function appendToCurrent($value, $key = null)
88: {
89: if($key === null){
90: $this->currentArray[] = $value;
91:
92: }else{
93: if (!is_numeric($key))
94: throw new \PHPixie\ORM\Exception\Model("Only numeric keys can be used.");
95:
96: $count = $this->count();
97:
98: if($key > $count)
99: throw new \PHPixie\ORM\Exception\Model("Only sequential keys can be used.");
100:
101: $this->currentArray[$key] = $value;
102: }
103:
104: return $value;
105: }
106:
107: }
108: