Completed
Pull Request — master (#59)
by
unknown
11:40
created

BaseRecord::getPK()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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