-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
LiteRecord.php
232 lines (205 loc) · 5.5 KB
/
LiteRecord.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
<?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;
/**
* Implementación de patrón ActiveRecord sin ayudantes de consultas SQL.
*/
abstract class LiteRecord extends BaseRecord
{
/**
* Obtener objeto por clave primaria, $var = Modelo($id).
*
* @param string $id valor para clave primaria
* @return self|false
*/
public function __invoke($id)
{
return self::get($id);
}
/**
* Invoca el callback.
*
* @param string $callback
*
* @return null|false
*/
protected function callback(string $callback)
{
if (\method_exists($this, $callback)) {
return $this->$callback();
}
}
/**
* Crear registro.
*
* @param array $data
*
* @throws \PDOException
* @return bool
*/
public function create(array $data = []): bool
{
$this->dump($data);
// Callback antes de crear
if ($this->callback('_beforeCreate') === \false) {
return \false;
}
$sql = QueryGenerator::insert($this, $data);
if ( ! self::prepare($sql)->execute($data)) {
return \false;
}
// Verifica si la PK es autogenerada
$pk = static::$pk;
if ( ! isset($this->$pk)) {
$this->$pk = QueryGenerator::query(
static::getDriver(),
'last_insert_id',
self::dbh(),
$pk,
static::getTable(),
static::getSchema()
);
}
// Callback despues de crear
$this->callback('_afterCreate');
return \true;
}
/**
* Actualizar registro.
*
* @param array $data
*
* @throws \KumbiaException
* @return bool
*/
public function update(array $data = []): bool
{
$this->dump($data);
// Callback antes de actualizar
if ($this->callback('_beforeUpdate') === \false) {
return \false;
}
$values = [];
$sql = QueryGenerator::update($this, $values);
if ( ! self::prepare($sql)->execute($values)) {
return \false;
}
// Callback despues de actualizar
$this->callback('_afterUpdate');
return \true;
}
/**
* Guardar registro.
*
* @param array $data
*
* @return bool
*/
public function save(array $data = []): bool
{
$this->dump($data);
if ($this->callback('_beforeSave') === \false) {
return \false;
}
$method = $this->saveMethod();
$result = $this->$method();
if ( ! $result) {
return \false;
}
$this->callback('_afterSave');
return \true;
}
/**
* Retorna el nombre del metodo a llamar durante un save (create o update).
*
* @return string
*/
protected function saveMethod(): string
{
return $this->hasPK() ? 'update' : 'create';
}
/**
* Eliminar registro por pk.
*
* @param string $pk valor para clave primaria
*
* @return bool
*/
public static function delete($pk): bool
{
$source = static::getSource();
$pkField = static::$pk;
// use pdo->execute()
return static::query("DELETE FROM $source WHERE $pkField = ?", [$pk])->rowCount() > 0;
}
/**
* Buscar por clave primaria.
*
* @param string $pk valor para clave primaria
* @param string $fields campos que se desean obtener separados por coma
*
* @return self|false
*/
public static function get(string $pk, string $fields = '*')
{
$sql = "SELECT $fields FROM ".static::getSource().' WHERE '.static::$pk.' = ?';
return static::query($sql, [$pk])->fetch();
}
/**
* Obtiene todos los registros de la consulta sql.
*
* @param string $sql
* @param array $values
*
* @return static[]
*/
public static function all(string $sql = '', array $values = []): array
{
if ( ! $sql) {
$sql = 'SELECT * FROM '.static::getSource();
}
return static::query($sql, $values)->fetchAll();
}
/**
* Obtiene el primer registro de la consulta sql.
*
* @param string $sql
* @param array $values
*
* @return static|false
*/
public static function first(string $sql, array $values = [])//: static in php 8
{
return static::query($sql, $values)->fetch();
}
/**
* Filtra las consultas.
*
* @param string $sql
* @param array $values
*
* @return array
*/
public static function filter(string $sql, array $values = []): array
{
$sql = "SELECT * FROM ".static::getSource()." $sql";
return static::all($sql, $values);
}
}