-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
ActiveRecord.php
397 lines (352 loc) · 10.9 KB
/
ActiveRecord.php
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
<?php
/**
* KumbiaPHP web & app Framework.
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://wiki.kumbiaphp.com/Licencia
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Kumbia
*
* @copyright 2005 - 2020 Kumbia Team (http://www.kumbiaphp.com)
* @license http://wiki.kumbiaphp.com/Licencia New BSD License
*/
namespace Kumbia\ActiveRecord;
/**
* Implementación de patrón ActiveRecord con ayudantes de consultas sql.
*/
class ActiveRecord extends LiteRecord implements \JsonSerializable
{
const BELONG_TO = 1;
const HAS_MANY = 2;
const HAS_ONE = 3;
/**
* Describe the relationships.
*
* @var array
*/
protected static $relations = [];
public static function resolver($relations, $obj)
{
$model = $relations->model;
if ($relations->type === self::HAS_MANY) {
return $model::allBy($relations->via, $obj->pk());
}
return $model::first($relations->via, $obj->pk());
}
public static function hasMany($name, $class, $via = null)
{
$str = strtolower($name);
$name = static::getTable();
static::$relations[$str] = (object) [
'model' => $class,
'type' => self::HAS_MANY,
'via' => $via ? $via : "{$name}_id",
];
}
public static function hasOne($name, $class, $via = null)
{
$str = strtolower($name);
$name = static::getTable();
static::$relations[$str] = (object) [
'model' => $class,
'type' => self::HAS_ONE,
'via' => $via ? $via : "{$name}_id",
];
}
/**
* json_encode() method.
*/
public function jsonSerialize()
{
return $this; //TODO: populate relations before
}
public function __get($key)
{
if (property_exists($this, $key)) {
return $this->$key;
}
//it's a relationship
if (isset(static::$relations[$key])) {
$this->populate($key);
return $this->$key;
}
return null; //TODO: change for error
}
protected static function getRelationship($rel)
{
if (!isset(static::$relations[$rel])) {
throw new \RuntimeException("Invalid relationship '$rel'", 500);
}
return static::$relations[$rel];
}
public function populate($rel)
{
$relations = static::getRelationship($rel);
$this->$rel = static::resolver($relations, $this);
}
/**
* Pagination of Results.
*
* @param array $params [description]
* @param array $values [description]
* @param int $page [description]
* @param int $per_page [description]
*
* @return Paginator [description]
*/
public static function pagination($params = [], $values = [], $page = 1, $per_page = 10)
{
$model = static::class;
unset($params['limit'], $params['offset']);
$sql = QueryGenerator::select($model::getSource(), $model::getDriver(), $params);
return new Paginator($model, $sql, $page, $per_page, $values);
}
/**
* Actualizar registros.
*
* @param array $fields
* @param string $where condiciones
* @param array $values valores para condiciones
*
* @return int numero de registros actualizados
*/
public static function updateAll(array $fields, string $where = '', array $values = [])
{
$sql = QueryGenerator::updateAll(static::class, $fields, $values, $where);
$sth = self::prepare($sql);
$sth->execute($values);
return $sth->rowCount();
}
/**
* Eliminar registro.
*
* @param string $where condiciones
* @param array |string $values valores
*
* @return int numero de registros eliminados
*/
public static function deleteAll($where = null, $values = null)
{
$source = static::getSource();
$sql = QueryGenerator::deleteAll($source, $where);
$sth = self::query($sql, $values);
return $sth->rowCount();
}
/**
* Elimina caracteres que podrian ayudar a ejecutar
* un ataque de Inyeccion SQL.
*
* @param string $sqlItem
*
* @return string
* @throws \RuntimeException
*/
public static function sqlItemSanitize($sqlItem)
{
$sqlItem = \trim($sqlItem);
if ($sqlItem !== '' && $sqlItem !== null) {
$sql_temp = \preg_replace('/\s+/', '', $sqlItem);
if (!\preg_match('/^[a-zA-Z0-9_\.]+$/', $sql_temp)) {
throw new \RuntimeException('Se está tratando de ejecutar un SQL peligroso!');
}
}
return $sqlItem;
}
/**
* Obtener la primera coincidencia por el campo indicado.
*
* @param string $field campo
* @param string $value valor
* @param array $params parametros adicionales
* order: criterio de ordenamiento
* fields: lista de campos
* join: joins de tablas
* group: agrupar campos
* having: condiciones de grupo
* offset: valor offset
*
* @return ActiveRecord
*/
public static function firstBy($field, $value, $params = [])
{
$field = self::sqlItemSanitize($field);
$params['where'] = "$field = ?";
return self::first($params, $value);
}
/**
* Obtener la primera coincidencia de las condiciones indicadas.
*
* @param array $params parametros adicionales
* order: criterio de ordenamiento
* fields: lista de campos
* group: agrupar campos
* join: joins de tablas
* having: condiciones de grupo
* offset: valor offset queda
* @param array $values valores de busqueda
*
* @return ActiveRecord
*/
public static function first($params = [], $values = [])
{
$args = func_get_args();
/*Reescribe el limit*/
$args[0]['limit'] = 1;
$res = self::doQuery($args);
return $res->fetch();
}
/**
* Obtener todos los registros.
*
* @param array $params
* where: condiciones where
* order: criterio de ordenamiento
* fields: lista de campos
* join: joins de tablas
* group: agrupar campos
* having: condiciones de grupo
* limit: valor limit
* offset: valor offset
* @param array $values valores de busqueda
*
* @return \PDOStatement
*/
public static function all($params = [], $values = [])
{
$res = self::doQuery(func_get_args());
return $res->fetchAll();
}
/**
* Do a query.
*
* @param array $array params of query
*
* @return \PDOStatement|false
*/
protected static function doQuery(array $array)
{
$params = self::getParam($array);
$values = self::getValues($array);
$sql = QueryGenerator::select(static::getSource(), static::getDriver(), $params);
$sth = static::query($sql, $values);
return $sth;
}
/**
* Retorna los parametros para el doQuery.
*
* @param array $array
*
* @return array
*/
protected static function getParam(array &$array)
{
$val = array_shift($array);
return is_null($val) ? [] : $val;
}
/**
* Retorna los values para el doQuery.
*
* @param array $array
*
* @return array
*/
protected static function getValues(array $array)
{
return isset($array[0]) ?
(is_array($array[0]) ? $array[0] : [$array[0]]) : $array;
}
/**
* Obtener todas las coincidencias por el campo indicado.
*
* @param string $field campo
* @param string $value valor
* @param array $params
* order: criterio de ordenamiento
* fields: lista de campos
* join: joins de tablas
* group: agrupar campos
* having: condiciones de grupo
* limit: valor limit
* offset: valor offset
*
* @return \PDOStatement
*/
public static function allBy($field, $value, $params = [])
{
$field = self::sqlItemSanitize($field);
$params['where'] = "$field = ?";
return self::all($params, $value);
}
/**
* Cuenta los registros que coincidan con las condiciones indicadas.
*
* @param string $where condiciones
* @param array $values valores
*
* @return int
*/
public static function count(string $where = '', array $values = [])
{
$source = static::getSource();
$sql = QueryGenerator::count($source, $where);
$sth = static::query($sql, $values);
return $sth->fetch()->count;
}
/**
* Paginar.
*
* @param array $params
* @param int $page numero de pagina
* @param int $perPage cantidad de items por pagina
* @param array $values valores
*
* @return Paginator
*/
public static function paginate(array $params, int $page, int $perPage, $values = null)
{
unset($params['limit'], $params['offset']);
$sql = QueryGenerator::select(static::getSource(), static::getDriver(), $params);
// Valores para consulta
if ($values !== null && !\is_array($values)) {
$values = \array_slice(func_get_args(), 3);
}
return new Paginator(static::class, $sql, $page, $perPage, $values);
}
/**
* Obtiene todos los registros de la consulta sql.
*
* @param string $sql
* @param string | array $values
*
* @return array
*/
public static function allBySql($sql, $values = null)
{
if (!is_array($values)) {
$values = \array_slice(\func_get_args(), 1);
}
return parent::all($sql, $values);
}
/**
* Obtiene el primer registro de la consulta sql.
*
* @param string $sql
* @param string | array $values
*
* @return array
*/
public static function firstBySql($sql, $values = null)
{
if (!is_array($values)) {
$values = \array_slice(\func_get_args(), 1);
}
return parent::first($sql, $values);
}
}