Completed
Push — master ( 229d9d...1c9390 )
by Alberto
01:52
created

BaseRecord   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 281
Duplicated Lines 2.49 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 7
Bugs 1 Features 1
Metric Value
wmc 28
c 7
b 1
f 1
lcom 1
cbo 3
dl 7
loc 281
rs 10

21 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A alias() 0 4 1
A getPK() 0 8 2
A getTable() 0 4 1
A getSource() 0 9 2
A getDatabase() 0 4 1
A dump() 0 6 2
A hasPK() 0 7 2
A getSchema() 0 4 1
A metadata() 0 9 1
A dbh() 0 4 1
A prepare() 0 7 1
A lastInsertId() 0 4 1
A sql() 0 7 1
A query() 0 13 4
A exists() 7 7 1
A paginateQuery() 0 4 1
A getDriver() 0 4 1
A begin() 0 4 1
A rollback() 0 4 1
A commit() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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