Completed
Push — master ( 2285ee...df6ef2 )
by joanhey
01:57
created

BaseRecord::__set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * KumbiaPHP web & app Framework.
4
 *
5
 * LICENSE
6
 *
7
 * This source file is subject to the new BSD license that is bundled
8
 * with this package in the file LICENSE.txt.
9
 * It is also available through the world-wide-web at this URL:
10
 * http://wiki.kumbiaphp.com/Licencia
11
 * If you did not receive a copy of the license and are unable to
12
 * obtain it through the world-wide-web, please send an email
13
 * to [email protected] so we can send you a copy immediately.
14
 *
15
 * @category   Kumbia
16
 *
17
 * @copyright  2005 - 2016 Kumbia Team (http://www.kumbiaphp.com)
18
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
19
 */
20
namespace Kumbia\ActiveRecord;
21
22
/**
23
 * Base del ORM ActiveRecord.
24
 */
25
class BaseRecord
26
{
27
    /**
28
     * Database por defecto usa default.
29
     *
30
     * @var string
31
     */
32
    protected static $database = 'default';
33
34
    /**
35
     * PK por defecto, si no existe mira en metadata.
36
     *
37
     * @var string
38
     */
39
    protected static $pk = 'id';
40
41
    /**
42
     * Constructor.
43
     *
44
     * @param array $data
45
     */
46
    public function __construct(array $data = [])
47
    {
48
        $this->dump($data);
49
    }
50
51
    /**
52
     * Get the Primary Key value for the object
53
     * @return mixed
54
     */
55
    public function pk(){
56
        $pk = static::getPK();
57
        return $this->$pk;
58
    }
59
60
    /**
61
     * Cargar datos al objeto.
62
     *
63
     * @param array $data
64
     */
65
    public function dump(array $data = [])
66
    {
67
        foreach ($data as $k => $v) {
68
            $this->$k = $v;
69
        }
70
    }
71
72
    /**
73
     * Alias de los campos.
74
     *
75
     * @return array
76
     */
77
    public static function alias()
78
    {
79
        return [];
80
    }
81
82
    /**
83
     * Verifica que PK este seteado.
84
     *
85
     * @throw \KumbiaException
86
     */
87
    protected function hasPK()
88
    {
89
        $pk = static::getPK();
90
        if (empty($this->$pk)) {
91
            throw new \KumbiaException(_('No se ha especificado valor para la clave primaria'));
92
        }
93
    }
94
95
    /**
96
     * Get the name of the primary key
97
     *
98
     * @return string
99
     */
100
    public static function getPK()
101
    {
102
        if (static::$pk) {
103
            return static::$pk;
104
        }
105
106
        return self::metadata()->getPK();
107
    }
108
109
    /**
110
     * Obtiene nombre de tabla en la bd.
111
     *
112
     * @return string smallcase del nombre de la clase
113
     */
114
    public static function getTable()
115
    {
116
        $split = explode('\\', \get_called_class());
117
        $table = preg_replace('/[A-Z]/', "_$0", lcfirst(end($split)));
118
        return strtolower($table);
119
    }
120
121
    /**
122
     * Obtiene el schema al que pertenece.
123
     *
124
     * @return string
125
     */
126
    public static function getSchema()
127
    {
128
        return '';
129
    }
130
131
    /**
132
     * Obtiene la combinación de esquema y tabla.
133
     *
134
     * @return string
135
     */
136
    public static function getSource()
137
    {
138
        $source = static::getTable();
139
        if ($schema = static::getSchema()) {
140
            $source = "$schema.$source";
141
        }
142
143
        return $source;
144
    }
145
146
    /**
147
     * Obtiene la conexión que se utilizará (contenidas en databases.php).
148
     *
149
     * @return string
150
     */
151
    public static function getDatabase()
152
    {
153
        return static::$database;
154
    }
155
156
    /**
157
     * Obtiene metadatos.
158
     *
159
     * @return Metadata\Metadata
160
     */
161
    public static function metadata()
162
    {
163
        return Metadata\Metadata::get(
164
            static::getDriver(),
165
            static::getDatabase(),
166
            static::getTable(),
167
            static::getSchema()
168
        );
169
    }
170
171
    /**
172
     * Obtiene manejador de conexion a la base de datos.
173
     *
174
     * @param bool $force forzar nueva conexion PDO
175
     *
176
     * @return \PDO
177
     */
178
    protected static function dbh($force = false)
179
    {
180
        return Db::get(static::getDatabase(), $force);
181
    }
182
183
    /**
184
     * Consulta sql preparada.
185
     *
186
     * @param string $sql
187
     *
188
     * @return \PDOStatement
189
     * @throw \PDOException
190
     */
191
    public static function prepare($sql)
192
    {
193
        $sth = self::dbh()->prepare($sql);
194
        $sth->setFetchMode(\PDO::FETCH_CLASS, \get_called_class());
195
196
        return $sth;
197
    }
198
199
    /**
200
     * Retorna el último ID insertado.
201
     *
202
     * @return ID
203
     */
204
    public static function lastInsertId()
205
    {
206
        return self::dbh()->lastInsertId();
207
    }
208
209
    /**
210
     * Consulta sql.
211
     *
212
     * @param string $sql
213
     *
214
     * @return \PDOStatement
215
     * @throw PDOException
216
     */
217
    public static function sql($sql)
218
    {
219
        $sth = self::dbh()->query($sql);
220
        $sth->setFetchMode(\PDO::FETCH_CLASS, \get_called_class());
221
222
        return $sth;
223
    }
224
225
    /**
226
     * Ejecuta consulta sql.
227
     *
228
     * @param string         $sql
229
     * @param array | string $values valores
230
     *
231
     * @return PDOStatement
232
     */
233
    public static function query($sql, $values = null)
234
    {
235
        if (func_num_args() === 1) {
236
            return self::sql($sql);
237
        }
238
239
        $sth = self::prepare($sql);
240
        if (!is_array($values)) {
241
            $values = \array_slice(\func_get_args(), 1);
242
        }
243
244
        return $sth->execute($values) ? $sth : false;
245
    }
246
247
    /**
248
     * Verifica si existe el registro.
249
     *
250
     * @param string $pk valor para clave primaria
251
     *
252
     * @return bool
253
     */
254 View Code Duplication
    public static function exists($pk)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
255
    {
256
        $source = static::getSource();
257
        $pkField = static::getPK();
258
259
        return self::query("SELECT COUNT(*) AS count FROM $source WHERE $pkField = ?", $pk)->fetch()->count > 0;
260
    }
261
262
    /**
263
     * Paginar consulta sql.
264
     *
265
     * @param string $sql     consulta select sql
266
     * @param int    $page    numero de pagina
267
     * @param int    $perPage cantidad de items por pagina
268
     * @param array  $values  valores
269
     *
270
     * @return Paginator
271
     */
272
    public static function paginateQuery($sql, $page, $perPage, $values = [])
273
    {
274
        return new Paginator(\get_called_class(), $sql, (int) $page, (int) $perPage, $values);
275
    }
276
277
    /**
278
     * Devuelve el nombre del drive PDO utilizado.
279
     *
280
     * @return string
281
     */
282
    public static function getDriver()
283
    {
284
        return self::dbh()->getAttribute(\PDO::ATTR_DRIVER_NAME);
285
    }
286
287
    /**
288
     * Comienza una trasacción.
289
     *
290
     * @return bool
291
     */
292
    public static function begin()
293
    {
294
        return self::dbh()->beginTransaction();
295
    }
296
297
    /**
298
     * Da marcha atrás a una trasacción.
299
     *
300
     * @return bool
301
     */
302
    public static function rollback()
303
    {
304
        return self::dbh()->rollBack();
305
    }
306
307
    /**
308
     * Realiza el commit de  una trasacción.
309
     *
310
     * @return bool
311
     */
312
    public static function commit()
313
    {
314
        return self::dbh()->commit();
315
    }
316
}
317