Completed
Push — master ( 168210...739816 )
by joanhey
02:01
created

BaseRecord::getAlias()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
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
     * Listado de los campos.
74
     *
75
     * @return array
76
     */
77
    public function getFields()
78
    {
79
        $fields = function ($obj) { return array_keys(get_object_vars($obj)); };
80
        return $fields ($this);
81
    }
82
83
    /**
84
     * Alias de los campos.
85
     *
86
     * @return array
87
     */
88
    public function getAlias()
89
    {
90
        return array_map('ucwords', $this->getFields());
91
    }
92
93
    /**
94
     * Verifica que PK este seteado.
95
     *
96
     * @throw \KumbiaException
97
     */
98
    protected function hasPK()
99
    {
100
        $pk = static::getPK();
101
        if (empty($this->$pk)) {
102
            throw new \KumbiaException(_('No se ha especificado valor para la clave primaria'));
103
        }
104
    }
105
106
    /**
107
     * Get the name of the primary key
108
     *
109
     * @return string
110
     */
111
    public static function getPK()
112
    {
113
        if (static::$pk) {
114
            return static::$pk;
115
        }
116
117
        return self::metadata()->getPK();
118
    }
119
120
    /**
121
     * Obtiene nombre de tabla en la bd.
122
     *
123
     * @return string smallcase del nombre de la clase
124
     */
125
    public static function getTable()
126
    {
127
        $split = explode('\\', \get_called_class());
128
        $table = preg_replace('/[A-Z]/', "_$0", lcfirst(end($split)));
129
        return strtolower($table);
130
    }
131
132
    /**
133
     * Obtiene el schema al que pertenece.
134
     *
135
     * @return string
136
     */
137
    public static function getSchema()
138
    {
139
        return '';
140
    }
141
142
    /**
143
     * Obtiene la combinación de esquema y tabla.
144
     *
145
     * @return string
146
     */
147
    public static function getSource()
148
    {
149
        $source = static::getTable();
150
        if ($schema = static::getSchema()) {
151
            $source = "$schema.$source";
152
        }
153
154
        return $source;
155
    }
156
157
    /**
158
     * Obtiene la conexión que se utilizará (contenidas en databases.php).
159
     *
160
     * @return string
161
     */
162
    public static function getDatabase()
163
    {
164
        return static::$database;
165
    }
166
167
    /**
168
     * Obtiene metadatos.
169
     *
170
     * @return Metadata\Metadata
171
     */
172
    public static function metadata()
173
    {
174
        return Metadata\Metadata::get(
175
            static::getDriver(),
176
            static::getDatabase(),
177
            static::getTable(),
178
            static::getSchema()
179
        );
180
    }
181
182
    /**
183
     * Obtiene manejador de conexion a la base de datos.
184
     *
185
     * @param bool $force forzar nueva conexion PDO
186
     *
187
     * @return \PDO
188
     */
189
    protected static function dbh($force = false)
190
    {
191
        return Db::get(static::getDatabase(), $force);
192
    }
193
194
    /**
195
     * Consulta sql preparada.
196
     *
197
     * @param string $sql
198
     *
199
     * @return \PDOStatement
200
     * @throw \PDOException
201
     */
202
    public static function prepare($sql)
203
    {
204
        $sth = self::dbh()->prepare($sql);
205
        $sth->setFetchMode(\PDO::FETCH_CLASS, \get_called_class());
206
207
        return $sth;
208
    }
209
210
    /**
211
     * Retorna el último ID insertado.
212
     *
213
     * @return ID
214
     */
215
    public static function lastInsertId()
216
    {
217
        return self::dbh()->lastInsertId();
218
    }
219
220
    /**
221
     * Consulta sql.
222
     *
223
     * @param string $sql
224
     *
225
     * @return \PDOStatement
226
     * @throw PDOException
227
     */
228
    public static function sql($sql)
229
    {
230
        $sth = self::dbh()->query($sql);
231
        $sth->setFetchMode(\PDO::FETCH_CLASS, \get_called_class());
232
233
        return $sth;
234
    }
235
236
    /**
237
     * Ejecuta consulta sql.
238
     *
239
     * @param string         $sql
240
     * @param array | string $values valores
241
     *
242
     * @return PDOStatement
243
     */
244
    public static function query($sql, $values = null)
245
    {
246
        if (func_num_args() === 1) {
247
            return self::sql($sql);
248
        }
249
250
        $sth = self::prepare($sql);
251
        if (!is_array($values)) {
252
            $values = \array_slice(\func_get_args(), 1);
253
        }
254
255
        return $sth->execute($values) ? $sth : false;
256
    }
257
258
    /**
259
     * Verifica si existe el registro.
260
     *
261
     * @param string $pk valor para clave primaria
262
     *
263
     * @return bool
264
     */
265 View Code Duplication
    public static function exists($pk)
0 ignored issues
show
Duplication introduced by joanhey
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...
266
    {
267
        $source = static::getSource();
268
        $pkField = static::getPK();
269
270
        return self::query("SELECT COUNT(*) AS count FROM $source WHERE $pkField = ?", $pk)->fetch()->count > 0;
271
    }
272
273
    /**
274
     * Paginar consulta sql.
275
     *
276
     * @param string $sql     consulta select sql
277
     * @param int    $page    numero de pagina
278
     * @param int    $perPage cantidad de items por pagina
279
     * @param array  $values  valores
280
     *
281
     * @return Paginator
282
     */
283
    public static function paginateQuery($sql, $page, $perPage, $values = [])
284
    {
285
        return new Paginator(\get_called_class(), $sql, (int) $page, (int) $perPage, $values);
286
    }
287
288
    /**
289
     * Devuelve el nombre del drive PDO utilizado.
290
     *
291
     * @return string
292
     */
293
    public static function getDriver()
294
    {
295
        return self::dbh()->getAttribute(\PDO::ATTR_DRIVER_NAME);
296
    }
297
298
    /**
299
     * Comienza una trasacción.
300
     *
301
     * @return bool
302
     */
303
    public static function begin()
304
    {
305
        return self::dbh()->beginTransaction();
306
    }
307
308
    /**
309
     * Da marcha atrás a una trasacción.
310
     *
311
     * @return bool
312
     */
313
    public static function rollback()
314
    {
315
        return self::dbh()->rollBack();
316
    }
317
318
    /**
319
     * Realiza el commit de  una trasacción.
320
     *
321
     * @return bool
322
     */
323
    public static function commit()
324
    {
325
        return self::dbh()->commit();
326
    }
327
}
328