flush
[m6w6/pq-gateway] / lib / pq / Gateway / Row.php
1 <?php
2
3 namespace pq\Gateway;
4
5 class Row implements \JsonSerializable
6 {
7 /**
8 * @var \pq\Gateway\Table
9 */
10 protected $table;
11
12 /**
13 * @var array
14 */
15 protected $data;
16
17 /**
18 * @var array
19 */
20 protected $mods = array();
21
22 /**
23 * @param \pq\Gateway\Table $table
24 * @param array $data
25 * @param bool $prime whether to mark all columns as modified
26 */
27 function __construct(Table $table, array $data = null, $prime = false) {
28 $this->table = $table;
29 $this->data = $data;
30
31 if ($prime) {
32 $this->prime();
33 }
34 }
35
36 /**
37 * Copy constructor
38 * @param array $data
39 * @return \pq\Gateway\Row
40 */
41 function __invoke(array $data) {
42 $that = clone $this;
43 $that->data = $data;
44 return $that->prime();
45 }
46
47 /**
48 * @implements JsonSerializable
49 * @return array
50 */
51 function jsonSerialize() {
52 return $this->data;
53 }
54
55 /**
56 * @return \pq\Gateway\Table
57 */
58 function getTable() {
59 return $this->table;
60 }
61
62 /**
63 * @return array
64 */
65 function getData() {
66 return $this->data;
67 }
68
69 /**
70 * Fill modified cells
71 * @return \pq\Gateway\Row
72 */
73 protected function prime() {
74 $this->mods = array();
75 foreach ($this->data as $key => $val) {
76 $this->mods[$key] = new Cell($this, $key, $val);
77 }
78 return $this;
79 }
80
81 /**
82 * Transform data array to where criteria
83 * @param array $data
84 * @return array
85 */
86 protected function criteria() {
87 $where = array();
88 array_walk($this->data, function($v, $k) use (&$where) {
89 $where["$k="] = $v;
90 });
91 return $where;
92 }
93
94 /**
95 * Get a cell
96 * @param string $p
97 * @return \pq\Gateway\Cell
98 */
99 function __get($p) {
100 if (!isset($this->mods[$p])) {
101 $this->mods[$p] = new Cell($this, $p, $this->data[$p]);
102 }
103 return $this->mods[$p];
104 }
105
106 /**
107 * Set a cell value
108 * @param string $p
109 * @param mixed $v
110 */
111 function __set($p, $v) {
112 $this->__get($p)->set(($v instanceof Cell) ? $v->get() : $v);
113 }
114
115 /**
116 * Create this row in the database
117 * @return \pq\Gateway\Row
118 */
119 function create() {
120 $this->data = $this->table->create($this->mods)->current()->data;
121 $this->mods = array();
122 return $this;
123 }
124
125 /**
126 * Update this row in the database
127 * @return \pq\Gateway\Row
128 */
129 function update() {
130 $this->data = $this->table->update($this->criteria(), $this->mods)->current()->data;
131 $this->mods = array();
132 return $this;
133 }
134
135 /**
136 * Delete this row in the database
137 * @return \pq\Gateway\Row
138 */
139 function delete() {
140 $this->data = $this->table->delete($this->criteria(), "*")->current()->data;
141 return $this->prime();
142 }
143 }