BaseRecord   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 299
Duplicated Lines 2.34 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 7
loc 299
rs 10
c 0
b 0
f 0
wmc 30
lcom 1
cbo 3

23 Methods

Rating   Name   Duplication   Size   Complexity  
A query() 0 13 4
A __construct() 0 4 1
A pk() 0 6 1
A dump() 0 6 2
A getFields() 0 4 1
A getAlias() 0 4 1
A hasPK() 0 7 2
A getPK() 0 8 2
A getTable() 0 7 1
A getSchema() 0 4 1
A getSource() 0 9 2
A getDatabase() 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 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
use KumbiaException;
23
24
/**
25
 * Base del ORM ActiveRecord.
26
 */
27
class BaseRecord
28
{
29
    /**
30
     * Database por defecto usa default.
31
     *
32
     * @var string
33
     */
34
    protected static $database = 'default';
35
36
    /**
37
     * PK por defecto, si no existe mira en metadata.
38
     *
39
     * @var string
40
     */
41
    protected static $pk = 'id';
42
43
    /**
44
     * Constructor.
45
     *
46
     * @param array $data
47
     */
48
    public function __construct(array $data = [])
49
    {
50
        $this->dump($data);
51
    }
52
53
    /**
54
     * Get the Primary Key value for the object
55
     * @return mixed
56
     */
57
    public function pk()
58
    {
59
        $pk = static::getPK();
60
61
        return $this->$pk;
62
    }
63
64
    /**
65
     * Cargar datos al objeto.
66
     *
67
     * @param array $data
68
     */
69
    public function dump(array $data = [])
70
    {
71
        foreach ($data as $k => $v) {
72
            $this->$k = $v;
73
        }
74
    }
75
76
    /**
77
     * Listado de los campos.
78
     *
79
     * @return array
80
     */
81
    public function getFields()
82
    {
83
        return \array_keys(\get_object_vars($this));
84
    }
85
86
    /**
87
     * Alias de los campos.
88
     *
89
     * @return array
90
     */
91
    public function getAlias()
92
    {
93
        return \array_map('ucwords', $this->getFields());
94
    }
95
96
    /**
97
     * Verifica que PK este seteado.
98
     *
99
     * @throws KumbiaException
100
     */
101
    protected function hasPK()
102
    {
103
        $pk = static::getPK();
104
        if (empty($this->$pk)) {
105
            throw new KumbiaException(_('No se ha especificado valor para la clave primaria'));
106
        }
107
    }
108
109
    /**
110
     * Get the name of the primary key
111
     *
112
     * @return string
113
     */
114
    public static function getPK()
115
    {
116
        if (static::$pk) {
117
            return static::$pk;
118
        }
119
120
        return self::metadata()->getPK();
121
    }
122
123
    /**
124
     * Obtiene nombre de tabla en la bd.
125
     *
126
     * @return string smallcase del nombre de la clase
127
     */
128
    public static function getTable()
129
    {
130
        $split = \explode('\\', \get_called_class());
131
        $table = \preg_replace('/[A-Z]/', '_$0', \lcfirst(\end($split)));
132
133
        return \strtolower($table);
134
    }
135
136
    /**
137
     * Obtiene el schema al que pertenece.
138
     *
139
     * @return string
140
     */
141
    public static function getSchema()
142
    {
143
        return '';
144
    }
145
146
    /**
147
     * Obtiene la combinación de esquema y tabla.
148
     *
149
     * @return string
150
     */
151
    public static function getSource()
152
    {
153
        $source = static::getTable();
154
        if ($schema = static::getSchema()) {
155
            $source = "$schema.$source";
156
        }
157
158
        return $source;
159
    }
160
161
    /**
162
     * Obtiene la conexión que se utilizará (contenidas en databases.php).
163
     *
164
     * @return string
165
     */
166
    public static function getDatabase()
167
    {
168
        return static::$database;
169
    }
170
171
    /**
172
     * Obtiene metadatos.
173
     *
174
     * @return Metadata\Metadata
175
     */
176
    public static function metadata()
177
    {
178
        return Metadata\Metadata::get(
179
            static::getDriver(),
180
            static::getDatabase(),
181
            static::getTable(),
182
            static::getSchema()
183
        );
184
    }
185
186
    /**
187
     * Obtiene manejador de conexion a la base de datos.
188
     *
189
     * @param  bool   $force forzar nueva conexion PDO
190
     * @return \PDO
191
     */
192
    protected static function dbh($force = \false)
193
    {
194
        return Db::get(static::getDatabase(), $force);
195
    }
196
197
    /**
198
     * Consulta sql preparada.
199
     *
200
     * @param  string          $sql
201
     * @throws \PDOException
202
     * @return \PDOStatement
203
     */
204
    public static function prepare($sql)
205
    {
206
        $sth = self::dbh()->prepare($sql);
207
        $sth->setFetchMode(\PDO::FETCH_CLASS, \get_called_class());
208
209
        return $sth;
210
    }
211
212
    /**
213
     * Retorna el último ID insertado.
214
     *
215
     * @return string
216
     */
217
    public static function lastInsertId()
218
    {
219
        return self::dbh()->lastInsertId();
220
    }
221
222
    /**
223
     * Consulta sql.
224
     *
225
     * @param  string          $sql
226
     * @throws \PDOException
227
     * @return \PDOStatement
228
     */
229
    public static function sql($sql)
230
    {
231
        $sth = self::dbh()->query($sql);
232
        $sth->setFetchMode(\PDO::FETCH_CLASS, \get_called_class());
233
234
        return $sth;
235
    }
236
237
    /**
238
     * Ejecuta consulta sql.
239
     *
240
     * @param  string               $sql
241
     * @param  array                |      string $values valores
242
     * @return bool|\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
     * @return bool
263
     */
264 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...
265
    {
266
        $source  = static::getSource();
267
        $pkField = static::getPK();
268
269
        return self::query("SELECT COUNT(*) AS count FROM $source WHERE $pkField = ?", $pk)->fetch()->count > 0;
270
    }
271
272
    /**
273
     * Paginar consulta sql.
274
     *
275
     * @param  string      $sql     consulta select sql
276
     * @param  int         $page    numero de pagina
277
     * @param  int         $perPage cantidad de items por pagina
278
     * @param  array       $values  valores
279
     * @return Paginator
280
     */
281
    public static function paginateQuery($sql, $page, $perPage, $values = [])
282
    {
283
        return new Paginator(\get_called_class(), $sql, (int) $page, (int) $perPage, $values);
284
    }
285
286
    /**
287
     * Devuelve el nombre del drive PDO utilizado.
288
     *
289
     * @return string
290
     */
291
    public static function getDriver()
292
    {
293
        return self::dbh()->getAttribute(\PDO::ATTR_DRIVER_NAME);
294
    }
295
296
    /**
297
     * Comienza una trasacción.
298
     *
299
     * @return bool
300
     */
301
    public static function begin()
302
    {
303
        return self::dbh()->beginTransaction();
304
    }
305
306
    /**
307
     * Da marcha atrás a una trasacción.
308
     *
309
     * @return bool
310
     */
311
    public static function rollback()
312
    {
313
        return self::dbh()->rollBack();
314
    }
315
316
    /**
317
     * Realiza el commit de  una trasacción.
318
     *
319
     * @return bool
320
     */
321
    public static function commit()
322
    {
323
        return self::dbh()->commit();
324
    }
325
}
326