This repository was archived by the owner on Apr 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObject_new.php
More file actions
355 lines (329 loc) · 11.4 KB
/
Object_new.php
File metadata and controls
355 lines (329 loc) · 11.4 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
<?php
namespace KORM;
use KORM\Connection;
class Object {
public static $_updateTableStructure = false;
public static $_tableNameWithNamespace = false;
private $_className;
protected static $_tableName;
private static $_cache = [];
protected $id = null;
private function __construct($id = null,$class=null) {
$this->_className = $class;
if (null==$id) {
$this->_constructNewRow($class);
} else {
$this->id = $id;
$query = 'select * from `' . self::_getTableName() . '` where `id`=?';
$pdo = Connection::prepare($query);
$pdo->execute([$id]);
$attrs = $pdo->fetchAll(\PDO::FETCH_ASSOC);
if (isset($attrs[0])) {
foreach ($attrs[0] as $key => $value) {
$this->$key = $value;
}
}
}
}
/**
*
* @param type $id
* @param type $nocache
* @return \KORM\Object
*/
static public function get($id = null, $nocache = false) {
$class = get_called_class();
$class::$_tableName = isset($class::$_tableName) ? $class::$_tableName : $class;
if (null==$id or $nocache) {
$object = new $class($id,$class);
return $object;
}
//test if object is in cache
if(!isset(self::$_cache[$class][$id])) {
$object = new $class($id,$class);
self::_cache($object);
} else {
$object = self::$_cache[$class][$id];
}
return $object;
}
private static function _cache($object){
//create an array for this class
if (!isset(self::$_cache[$object->_className])) {
self::$_cache[$object->_className] = [];
}
self::$_cache[$object->_className][$object->id]=$object;
}
/**
*
* @param String $name
* @param array $arguments
* @return Object
*/
public function __call($name, $arguments) {
if (substr($name, 0, 3) == 'set') {
$key = strtolower(substr($name, 3, 1)) . substr($name, 4);
$this->$key = $arguments[0];
}
return $this;
}
public function isInDatabase() {
return is_numeric($this->id) and $this->id != 0;
}
public function populate($values) {
foreach ($values as $key => $value) {
$this->$key = $value;
}
}
public function store() {
$vars = get_object_vars($this);
/**
* table creation or update
*/
if (self::$_updateTableStructure) {
if (!self::_tableExists()) {
self::_createTable();
}
//create fields
$this->_createColumns();
}
/**
* convert attributes to database data
*/
foreach ($vars as $key => $value) {
if (substr($key, 0, 1) == '_' or $key == 'id') {
unset($vars[$key]);
}
if (is_object($value)) {
$vars[$key . '_id'] = $value->id;
unset($vars[$key]);
}
if (is_array($value)) {
unset($vars[$key]);
}
}
/**
* create and execute query
*/
if (!$this->isInDatabase()) {
$query = 'insert into `' . self::_getTableName() . '`(`' . implode('`, `', array_keys($vars)) . '`) values (?' . str_repeat(', ?', sizeof($vars) - 1) . ')';
$statement = Connection::prepare($query);
$result = $statement->execute(array_values($vars));
if (!$result) {
throw new \Exception($statement->errorInfo()[2]);
}
$this->id = Connection::lastInsertId();
} else {
$query = 'update `' . self::_getTable() . '` set `' . implode('` = ?, `', array_keys($vars)) . '` = ? '
. 'where `id` = ?';
$statement = Connection::prepare($query);
$vars['id'] = $this->$id;
$result = $statement->execute(array_values($vars));
if (!$result) {
throw new \Exception($statement->errorInfo()[2]);
}
}
self::_cache($this);
return $this;
}
public static function count($params = []) {
$query = 'select count(*) from `' . self::_getTableName() . '` ';
$where = [];
$p = [];
if (count($params) > 0) {
foreach ($params as $key => $value) {
$where[] = '`' . $key . '`=?';
$p[] = $value;
}
$query .= 'where ' . implode(' and ', $where);
}
$statement = Connection::prepare($query);
$statement->execute($p);
$result = $statement->fetchAll(\PDO::FETCH_COLUMN);
return $result[0];
}
private function _constructNewRow(String $class) {
$vars = $class::_getColumns($class::_getTableName());
var_dump($vars);
foreach ($vars as $value) {
$key = $value['Field'];
$this->$key = $value['Default'];
}
}
/**
* drop table
* @param boolean $foreignKeyCheck
* @return PDOStatement
*/
public static function drop($foreignKeyCheck = true) {
if (!$foreignKeyCheck) {
Connection::exec('SET FOREIGN_KEY_CHECKS = 0;');
}
$return = Connection::exec('drop table `' . self::_getTableName() . '`;');
if (!$foreignKeyCheck) {
Connection::exec('SET FOREIGN_KEY_CHECKS = 1;');
}
return $return;
}
/**
* truncate table
* @param boolean $foreignKeyCheck
* @return PDOStatement
*/
public static function truncate($foreignKeyCheck = true) {
if (!$foreignKeyCheck) {
Connection::exec('SET FOREIGN_KEY_CHECKS = 0;');
}
$return = Connection::exec('truncate `' . self::_getTableName() . '`;');
if (!$foreignKeyCheck) {
Connection::exec('SET FOREIGN_KEY_CHECKS = 1;');
}
return $return;
}
//------------------------
// Table structure
//------------------------
protected static function _getTableName() {
$class = get_called_class();
if (isset($class::$_table)) {
return $class::$_table;
} else {
$array = explode('\\', $class);
return strtolower($array[count($array) - 1]);
}
}
/**
* execute a query
* @param string $query
* @param array $params
* @return integer
*/
public static function exec($query, $params) {
$statement = Connection::prepare($query);
$statement->execute($params);
return $statement->rowCount();
}
/**
* create table if not exists
* @return type
*/
private static function _createTable() {
return self::exec('create table ' . self::_getTableName() . '(`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY)', []);
}
/**
* return true if table exists
* @return boolean
*/
public static function _tableExists() {
$query = 'show tables like "' . self::_getTableName() . '"';
return sizeof(Connection::fetchAll($query)) > 0;
}
/**
* get columns informations
* @param string $table
* @return array
*/
public static function _getColumns($table = null) {
if (is_null($table)) {
$table = self::_getTableName();
}
$query = 'show columns from `' . $table . '`';
if (self::_tableExists()) {
return Connection::query($query)->fetchAll(\PDO::FETCH_ASSOC);
} else {
return [];
}
}
/**
* return column type
* @param string $value
* @return string
*/
private static function _getColumnType($value) {
$type = 'longtext';
switch (gettype($value)) {
case 'boolean':
$type = 'tinyint(1)';
break;
case 'integer':
$type = 'int(11)';
break;
case 'double':
$type = 'float';
break;
case 'string':
if (\DateTime::createFromFormat('Y-m-d', $value)) {
$type = 'date';
} elseif (\DateTime::createFromFormat('H:i:s', $value) or \DateTime::createFromFormat('H:i', $value)) {
$type = 'time';
} elseif (\DateTime::createFromFormat('Y-m-d H:i:s', $value) or \DateTime::createFromFormat('Y-m-d H:i', $value)) {
$type = 'datetime';
} elseif (is_numeric($value)) {
if (intval($value) == $value) {
return self::_getColumnType(intval($value));
} else {
return self::_getColumnType(floatval($value));
}
} elseif (strlen($value) > 250) {
$type = 'longtext';
} else {
$type = 'varchar(250)';
}
}
return $type;
}
/**
* create columns from attributes value
*/
private function _createColumns() {
$columns = self::_getColumns();
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (substr($key, 0, 1) != '_') {
$trouve = false;
$name = $key;
$type = self::_getColumnType($value);
$index = '';
$null = '';
$foreignKey = false;
if (is_object($value)) {
$name .= '_id';
$referenceClass = get_class($value);
$value = $value->id;
$type = 'int(11)';
$null = 'NULL';
$index = ', ADD INDEX(`' . $name . '`)';
$foreignKey = true;
$referenceTable = $referenceClass::_getTableName();
}
if (is_array($value)) {
$trouve = true;
$value = 'NULL';
}
foreach ($columns as $column) {
if ($column['Field'] == $name) {
$trouve = true;
$c = $column;
}
}
//create field
if (!$trouve) {
//ALTER TABLE `board` ADD `label` VARCHAR(200) NOT NULL AFTER `id`;
self::exec('ALTER TABLE `' . self::_getTableName() . '` ADD `' . $name . '` ' . $type . ' ' . ' ' . $null . ' ' . $index, []);
if ($foreignKey) {
self::exec('ALTER TABLE `' . self::_getTableName() . '` ADD FOREIGN KEY (`' . $name . '`) REFERENCES `' . $referenceTable . '`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;', []);
}
} elseif (isset($c)) {
if ($type != $c['Type'] and $value !== 'NULL' and ! is_null($value)) {
$dataTypes = ['tinyint(1)', 'int(11)', 'float', 'date', 'time', 'datetime', 'varchar(250)', 'longtext'];
//update field
if (array_search($c['Type'], $dataTypes) < array_search($type, $dataTypes)) {
self::exec('ALTER TABLE `' . self::_getTableName() . '` CHANGE `' . $name . '` `' . $name . '` ' . $type, []);
}
}
}
unset($c);
}
}
}
}