1 <?php
2 3 4 5 6 7 8 9 10
11
12 namespace Neevo;
13
14 use ArrayAccess;
15 use ArrayIterator;
16 use Countable;
17 use IteratorAggregate;
18
19
20 21 22 23
24 class Row implements ArrayAccess, Countable, IteratorAggregate {
25
26
27
28 protected $frozen;
29
30
31 protected $primary;
32
33
34 protected $data = array();
35
36
37 protected $modified = array();
38
39
40 protected $table;
41
42
43 protected $connection;
44
45
46 47 48 49 50
51 public function __construct(array $data, Result $result){
52 $this->data = $data;
53 $this->connection = $result->getConnection();
54 $this->table = $result->getTable();
55 $this->primary = $result->getPrimaryKey();
56 $this->frozen = !$this->table || !$this->primary || !isset($this->data[$this->primary]);
57 }
58
59
60 61 62 63 64
65 public function update(){
66 if($this->frozen)
67 throw new NeevoException('Update disabled - cannot get primary key or table.');
68
69 if(!empty($this->modified)){
70 return Statement::createUpdate($this->connection, $this->table, $this->modified)
71 ->where($this->primary, $this->data[$this->primary])->limit(1)->affectedRows();
72 }
73 return 0;
74 }
75
76
77 78 79 80 81
82 public function delete(){
83 if($this->frozen)
84 throw new NeevoException('Delete disabled - cannot get primary key or table.');
85
86 return Statement::createDelete($this->connection, $this->table)
87 ->where($this->primary, $this->data[$this->primary])->limit(1)->affectedRows();
88 }
89
90
91 92 93 94
95 public function toArray(){
96 return array_merge($this->data, $this->modified);
97 }
98
99
100 101 102 103
104 public function isFrozen(){
105 return (bool) $this->frozen;
106 }
107
108
109 public function count(){
110 return count(array_merge($this->data, $this->modified));
111 }
112
113
114 115 116
117 public function getIterator(){
118 return new ArrayIterator(array_merge($this->data, $this->modified));
119 }
120
121
122 public function __get($name){
123 return array_key_exists($name, $this->modified)
124 ? $this->modified[$name] : (isset($this->data[$name])
125 ? $this->data[$name] : null);
126 }
127
128
129 public function __set($name, $value){
130 $this->modified[$name] = $value;
131 }
132
133
134 public function __isset($name){
135 return isset($this->data[$name]) || isset($this->modified[$name]);
136 }
137
138
139 public function __unset($name){
140 $this->modified[$name] = null;
141 }
142
143
144 public function offsetGet($offset){
145 return $this->__get($offset);
146 }
147
148
149 public function offsetSet($offset, $value){
150 $this->__set($offset, $value);
151 }
152
153
154 public function offsetExists($offset){
155 return $this->__isset($offset);
156 }
157
158
159 public function offsetUnset($offset){
160 $this->__unset($offset);
161 }
162
163
164 }
165