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

ActiveRecord::sqlItemSanitize()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 12
rs 9.2
cc 4
eloc 7
nc 3
nop 1
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
 * Implementación de patrón ActiveRecord con ayudantes de consultas sql.
24
 */
25
class ActiveRecord extends LiteRecord
26
{
27
    /**
28
     * Actualizar registros.
29
     *
30
     * @param array  $fields
31
     * @param string $where  condiciones
32
     * @param array  $values valores para condiciones
33
     *
34
     * @return int numero de registros actualizados
35
     */
36 View Code Duplication
    public static function updateAll(array $fields, $where = null, array $values = [])
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...
37
    {
38
        if ($values !== null && !is_array($values)) {
39
            $values = \array_slice(\func_get_args(), 2);
40
        }
41
        $sql = QueryGenerator::updateAll(\get_called_class(), $fields, $values, $where);
42
        $sth = self::prepare($sql);
43
        $sth->execute($values);
44
45
        return $sth->rowCount();
46
    }
47
48
    /**
49
     * Eliminar registro.
50
     *
51
     * @param string        $where  condiciones
52
     * @param array |string $values valores
53
     *
54
     * @return int numero de registros eliminados
55
     */
56
    public static function deleteAll($where = null, $values = null)
57
    {
58
        $source = static::getSource();
59
        $sql = QueryGenerator::deleteAll($source, $where);
60
        $sth = self::query($sql, $values);
61
62
        return $sth->rowCount();
63
    }
64
65
    /**
66
     * Elimina caracteres que podrian ayudar a ejecutar
67
     * un ataque de Inyeccion SQL.
68
     *
69
     * @param string $sqlItem
70
     *
71
     * @return string
72
     * @throw KumbiaException
73
     */
74
    public static function sqlItemSanitize($sqlItem)
75
    {
76
        $sqlItem = \trim($sqlItem);
77
        if ($sqlItem !== '' && $sqlItem !== null) {
78
            $sql_temp = \preg_replace('/\s+/', '', $sqlItem);
79
            if (!\preg_match('/^[a-zA-Z0-9_\.]+$/', $sql_temp)) {
80
                throw new \KumbiaException('Se esta tratando de ejecutar una operacion maliciosa!');
81
            }
82
        }
83
84
        return $sqlItem;
85
    }
86
87
    /**
88
     * Obtener la primera coincidencia por el campo indicado.
89
     *
90
     * @param string $field  campo
91
     * @param string $value  valor
92
     * @param array  $params parametros adicionales
93
     *                       order: criterio de ordenamiento
94
     *                       fields: lista de campos
95
     *                       join: joins de tablas
96
     *                       group: agrupar campos
97
     *                       having: condiciones de grupo
98
     *                       offset: valor offset
99
     *
100
     * @return ActiveRecord
101
     */
102 View Code Duplication
    public static function firstBy($field, $value, $params = [])
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...
103
    {
104
        $field = self::sqlItemSanitize($field);
105
        $params['where'] = "$field = ?";
106
107
        return self::first($params, $value);
108
    }
109
110
    /**
111
     * Obtener la primera coincidencia de las condiciones indicadas.
112
     *
113
     * @param array  $params parametros de bus
114
     * @param string $field  campo
0 ignored issues
show
Bug introduced by
There is no parameter named $field. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
115
     * @param string $value  valor
0 ignored issues
show
Documentation introduced by
There is no parameter named $value. Did you maybe mean $values?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
116
     * @param array  $params parametros adicionales
117
     *                       order: criterio de ordenamiento
118
     *                       fields: lista de campos
119
     *                       group: agrupar campos
120
     *                       join: joins de tablas
121
     *                       having: condiciones de grupo
122
     *                       offset: valor offset queda
123
     * @param array  $values valores de busqueda
124
     *
125
     * @return ActiveRecord
126
     */
127
    public static function first($params = [], $values = [])
128
    {
129
        $args = func_get_args();
130
        /*Reescribe el limit*/
131
        $args[0]['limit'] = 1;
132
        $res = self::doQuery($args);
133
134
        return $res->fetch();
135
    }
136
137
    /**
138
     * Obtener todos los registros.
139
     *
140
     * @param array $params
141
     *                      where: condiciones where
142
     *                      order: criterio de ordenamiento
143
     *                      fields: lista de campos
144
     *                      join: joins de tablas
145
     *                      group: agrupar campos
146
     *                      having: condiciones de grupo
147
     *                      limit: valor limit
148
     *                      offset: valor offset
149
     * @param array $values valores de busqueda
150
     *
151
     * @return \PDOStatement
152
     */
153
    public static function all($params = [], $values = [])
154
    {
155
        $res = self::doQuery(func_get_args());
156
157
        return $res->fetchAll();
158
    }
159
160
    /**
161
     * Do a query.
162
     *
163
     * @param array $array params of query
164
     *
165
     * @return \PDOStatement|false
166
     */
167
    protected static function doQuery(array $array)
168
    {
169
        $params = self::getParam($array);
170
        $values = self::getValues($array);
171
        $sql = QueryGenerator::select(static::getSource(), static::getDriver(), $params);
172
        $sth = static::query($sql, $values);
173
174
        return $sth;
175
    }
176
177
    /**
178
     * Retorna los parametros para el doQuery.
179
     *
180
     * @param array $array
181
     *
182
     * @return array
183
     */
184
    protected static function getParam(array &$array)
185
    {
186
        $val = array_shift($array);
187
188
        return is_null($val) ?  [] : $val;
189
    }
190
191
    /**
192
     * Retorna los values para el doQuery.
193
     *
194
     * @param array $array
195
     *
196
     * @return array
197
     */
198
    protected static function getValues(array $array)
199
    {
200
        return isset($array[0]) ?
201
            is_array($array[0]) ? $array[0] : [$array[0]]: $array;
202
    }
203
204
    /**
205
     * Obtener todas las coincidencias por el campo indicado.
206
     *
207
     * @param string $field  campo
208
     * @param string $value  valor
209
     * @param array  $params
210
     *                       order: criterio de ordenamiento
211
     *                       fields: lista de campos
212
     *                       join: joins de tablas
213
     *                       group: agrupar campos
214
     *                       having: condiciones de grupo
215
     *                       limit: valor limit
216
     *                       offset: valor offset
217
     *
218
     * @return \PDOStatement
219
     */
220 View Code Duplication
    public static function allBy($field, $value, $params = [])
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...
221
    {
222
        $field = self::sqlItemSanitize($field);
223
        $params['where'] = "$field = ?";
224
225
        return self::all($params, $value);
226
    }
227
228
    /**
229
     * Cuenta los registros que coincidan con las condiciones indicadas.
230
     *
231
     * @param string $where  condiciones
232
     * @param array  $values valores
233
     *
234
     * @return int
235
     */
236 View Code Duplication
    public static function count($where = null, $values = null)
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...
237
    {
238
        $source = static::getSource();
239
        $sql = QueryGenerator::count($source, $where);
240
        if ($values !== null && !is_array($values)) {
241
            $values = \array_slice(\func_get_args(), 1);
242
        }
243
        $sth = static::query($sql, $values);
244
245
        return $sth->fetch()->count;
246
    }
247
248
    /**
249
     * Paginar.
250
     *
251
     * @param array $params
252
     * @param int   $page    numero de pagina
253
     * @param int   $perPage cantidad de items por pagina
254
     * @param array $values  valores
255
     *
256
     * @return Paginator
257
     */
258
    public static function paginate(array $params, $page, $perPage, $values = null)
259
    {
260
        unset($params['limit'], $params['offset']);
261
        $sql = QueryGenerator::select(static::getSource(), static::getDriver(), $params);
262
263
        // Valores para consulta
264
        if ($values !== null && !\is_array($values)) {
265
            $values = \array_slice(func_get_args(), 3);
266
        }
267
268
        return new Paginator(\get_called_class(), $sql, (int) $page, (int) $perPage, $values);
269
    }
270
271
    /**
272
     * Obtiene todos los registros de la consulta sql.
273
     *
274
     * @param string         $sql
275
     * @param string | array $values
276
     *
277
     * @return array
278
     */
279 View Code Duplication
    public static function allBySql($sql, $values = null)
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...
280
    {
281
        if (!is_array($values)) {
282
            $values = \array_slice(\func_get_args(), 1);
283
        }
284
285
        return parent::all($sql, $values);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (all() instead of allBySql()). Are you sure this is correct? If so, you might want to change this to $this->all().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
286
    }
287
288
    /**
289
     * Obtiene el primer registro de la consulta sql.
290
     *
291
     * @param string         $sql
292
     * @param string | array $values
293
     *
294
     * @return array
295
     */
296 View Code Duplication
    public static function firstBySql($sql, $values = null)
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...
297
    {
298
        if (!is_array($values)) {
299
            $values = \array_slice(\func_get_args(), 1);
300
        }
301
302
        return parent::first($sql, $values);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (first() instead of firstBySql()). Are you sure this is correct? If so, you might want to change this to $this->first().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
303
    }
304
}
305