-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathBaseRecord.php
333 lines (297 loc) · 7.23 KB
/
BaseRecord.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
<?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 - 2016 Kumbia Team (http://www.kumbiaphp.com)
* @license http://wiki.kumbiaphp.com/Licencia New BSD License
*/
namespace Kumbia\ActiveRecord;
use \PDO;
use \PDOStatement;
use \PDOException;
/**
* Base del ORM ActiveRecord.
*/
#[\AllowDynamicProperties]
abstract class BaseRecord
{
public const VERSION = '0.5.8';
/**
* Database por defecto usa default.
*
* @var string
*/
protected static $database = 'default';
/**
* Nombre de la tabla.
*
* @var string
*/
protected static $table = '';
/**
* PK por defecto, si no existe mira en metadata.
*
* @var string|null
*/
protected static $pk = 'id';
/**
* Constructor.
*
* @param array $data
*/
public function __construct(array $data = [])
{
$this->dump($data);
}
/**
* Get the Primary Key value for the object
* @return string
*/
public function pk(): string
{
return $this->{static::$pk};
}
/**
* Cargar datos al objeto.
*
* @param array $data
*/
public function dump(array $data = []): void
{
foreach ($data as $k => $v) {
$this->$k = $v;
}
}
/**
* Listado de los campos.
*
* @return string[]
*/
public function getFields(): array
{
return \array_keys(\get_object_vars($this));
}
/**
* Alias de los campos.
*
* @return string[]
*/
public function getAlias(): array
{
//$humanize = function ()
return \array_map('\ucwords', $this->getFields());
}
/**
* Verifica que PK este seteado.
*
* @return bool
*/
protected function hasPK(): bool
{
return isset($this->{static::$pk});
}
/**
* Get the name of the primary key
*
* @return string
*/
public static function getPK(): string
{
return static::$pk ?? static::$pk = self::metadata()->getPK();
}
/**
* Obtiene nombre de tabla en la bd.
*
* @return string smallcase del nombre de la clase
*/
public static function getTable(): string
{
if (static::$table) {
return static::$table;
}
$split = \explode('\\', static::class);
$table = \preg_replace('/[A-Z]/', '_$0', \lcfirst(\end($split)));
return static::$table = \strtolower($table);
}
/**
* Obtiene el schema al que pertenece.
*
* @return string
*/
public static function getSchema(): string
{
return '';
}
/**
* Obtiene la combinación de esquema y tabla.
*
* @return string
*/
public static function getSource(): string
{
$source = static::getTable();
if ($schema = static::getSchema()) {
$source = "$schema.$source";
}
return $source;
}
/**
* Obtiene la conexión que se utilizará (contenidas en databases.php).
*
* @return string
*/
public static function getDatabase(): string
{
return static::$database;
}
/**
* Obtiene metadatos.
*
* @return Metadata\Metadata
*/
public static function metadata(): Metadata\Metadata
{
return Metadata\Metadata::get(
static::getDatabase(),
static::getTable(),
static::getSchema()
);
}
/**
* Obtiene manejador de conexion a la base de datos.
*
* @return \PDO
*/
protected static function dbh(): \PDO
{
return Db::get(static::getDatabase());
}
/**
* Consulta sql preparada.
*
* @param string $sql
*
* @throws \PDOException
* @return \PDOStatement
*/
public static function prepare(string $sql): PDOStatement
{
$sth = self::dbh()->prepare($sql);
$sth->setFetchMode(\PDO::FETCH_CLASS, static::class);
return $sth;
}
/**
* Retorna el último ID insertado.
*
* @return string
*/
public static function lastInsertId(): string
{
return self::dbh()->lastInsertId();
}
/**
* Consulta sql.
*
* @param string $sql
*
* @throws \PDOException
* @return \PDOStatement
*/
public static function sql(string $sql): PDOStatement
{
return self::dbh()->query($sql, \PDO::FETCH_CLASS, static::class);
}
/**
* Ejecuta consulta sql.
*
* @param string $sql
* @param array $values valores
*
* @throws PDOException
* @return bool|PDOStatement
*/
public static function query(string $sql, array $values = [])
{
if (empty($values)) {
return self::sql($sql);
}
$sth = self::prepare($sql);
return $sth->execute($values) ? $sth : \false;
}
/**
* Verifica si existe el registro.
*
* @param string $pk valor para clave primaria
* @return bool
*/
public static function exists($pk): bool
{
$source = static::getSource();
$pkField = static::getPK();
return self::query("SELECT COUNT(*) AS count FROM $source WHERE $pkField = ?", [$pk])->fetch()->count > 0;
}
/**
* Paginar consulta sql.
*
* @param string $sql consulta select sql
* @param int $page numero de pagina
* @param int $perPage cantidad de items por pagina
* @param array $values valores
* @return Paginator
*/
public static function paginateQuery(string $sql, int $page, int $perPage, array $values = []): Paginator
{
return new Paginator(static::class, $sql, $page, $perPage, $values);
}
/**
* Devuelve el nombre del drive PDO utilizado.
*
* @return string
*/
public static function getDriver(): string
{
return self::dbh()->getAttribute(\PDO::ATTR_DRIVER_NAME);
}
/**
* Comienza una trasacción.
*
* @throws PDOException If there is already a transaction started or the driver does not support transactions
* @return bool
*/
public static function begin(): bool
{
return self::dbh()->beginTransaction();
}
/**
* Da marcha atrás a una trasacción.
*
* @throws PDOException if there is no active transaction.
* @return bool
*/
public static function rollback(): bool
{
return self::dbh()->rollBack();
}
/**
* Realiza el commit de una trasacción.
*
* @throws \PDOException if there is no active transaction.
* @return bool
*/
public static function commit(): bool
{
return self::dbh()->commit();
}
}