Completed
Pull Request — master (#61)
by joanhey
14:45 queued 08:22
created

LiteRecord::create()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 1
Metric Value
c 5
b 1
f 1
dl 0
loc 25
rs 8.5806
cc 4
eloc 12
nc 4
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  Copyright (c) 2005-2014 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 sin ayudantes de consultas SQL.
24
 */
25
class LiteRecord extends BaseRecord
26
{
27
    /**
28
     * Obtener objeto por clave primaria, $var = Modelo($id).
29
     *
30
     * @param string $id valor para clave primaria
31
     *
32
     * @return ActiveRecord
33
     */
34
    public function __invoke($id)
35
    {
36
        return self::get($id);
37
    }
38
39
    /**
40
     * Invoca el callback.
41
     *
42
     * @param string $callback
43
     *
44
     * @return mixed
45
     */
46
    protected function callback($callback)
47
    {
48
        if (\method_exists($this, $callback)) {
49
            return $this->$callback();
50
        }
51
    }
52
53
    /**
54
     * Crear registro.
55
     *
56
     * @param array $data
57
     *
58
     * @return bool
59
     * @throw PDOException
60
     */
61
    public function create(array $data = [])
62
    {
63
        $this->dump($data);
64
65
        // Callback antes de crear
66
        if ($this->callback('_beforeCreate') === false) {
67
            return false;
68
        }
69
70
        $sql = QueryGenerator::insert($this, $data);
71
72
        if (!self::prepare($sql)->execute($data)) {
73
            return false;
74
        }
75
76
        // Verifica si la PK es autogenerada
77
        $pk = static::getPK();
78
        if (!isset($this->$pk)) {
79
            $this->$pk = QueryGenerator::query(static::getDriver(), 'last_insert_id', self::dbh(), $pk, static::getTable(), static::getSchema());
80
        }
81
        // Callback despues de crear
82
        $this->callback('_afterCreate');
83
84
        return true;
85
    }
86
87
    /**
88
     * Actualizar registro.
89
     *
90
     * @param array $data
91
     *
92
     * @return bool
93
     */
94
    public function update(array $data = [])
95
    {
96
        $this->dump($data);
97
        // Callback antes de actualizar
98
        if ($this->callback('_beforeUpdate') === false) {
99
            return false;
100
        }
101
        $this->hasPK();
102
        $values = [];
103
        $sql = QueryGenerator::update($this, $values);
104
        //var_dump($values);var_dump($sql);die;
105
        if (!self::prepare($sql)->execute($values)) {
106
            return false;
107
        }
108
        // Callback despues de actualizar
109
        $this->callback('_afterUpdate');
110
111
        return true;
112
    }
113
114
    /**
115
     * Guardar registro.
116
     *
117
     * @param array $data
118
     *
119
     * @return bool
120
     */
121
    public function save(array $data = [])
122
    {
123
        $this->dump($data);
124
125
        if ($this->callback('_beforeSave') === false) {
126
            return false;
127
        }
128
129
        $method = $this->saveMethod();
130
        $result = $this->$method();
131
132
        if (!$result) {
133
            return false;
134
        }
135
136
        $this->callback('_afterSave');
137
138
        return true;
139
    }
140
141
    /**
142
     * Retorna el nombre del metodo a llamar durante un save (create o update).
143
     *
144
     * @return string
145
     */
146
    protected function saveMethod()
147
    {
148
        $pk = static::getPK();
149
150
        return (empty($this->$pk) || !static::exists($this->$pk)) ?
151
            'create' : 'update';
152
    }
153
154
    /**
155
     * Eliminar registro por pk.
156
     *
157
     * @param int $pk valor para clave primaria
158
     *
159
     * @return bool
160
     */
161 View Code Duplication
    public static function delete($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...
162
    {
163
        $source = static::getSource();
164
        $pkField = static::getPK();
165
166
        return static::query("DELETE FROM $source WHERE $pkField = ?", (int) $pk)->rowCount() > 0;
167
    }
168
169
    /**
170
     * Buscar por clave primaria.
171
     *
172
     * @param string $pk     valor para clave primaria
173
     * @param string $fields campos que se desean obtener separados por coma
174
     *
175
     * @return LiteRecord
176
     */
177
    public static function get($pk, $fields = '*')
178
    {
179
        $source = static::getSource();
180
        $pkField = static::getPK();
181
182
        $sql = "SELECT $fields FROM $source WHERE $pkField = ?";
183
184
        return static::query($sql, $pk)->fetch();
185
    }
186
187
    /**
188
     * Obtiene todos los registros de la consulta sql.
189
     *
190
     * @param string         $sql
191
     * @param string | array $values
192
     *
193
     * @return array
194
     */
195
    public static function all($sql = '', $values = null)
196
    {
197
        if (!$sql) {
198
            $source = static::getSource();
199
            $sql = "SELECT * FROM $source";
200
        }
201
202
        return static::query($sql, $values)->fetchAll();
203
    }
204
205
    /**
206
     * Obtiene el primer registro de la consulta sql.
207
     *
208
     * @param string         $sql
209
     * @param string | array $values
210
     *
211
     * @return array
212
     */
213
    public static function first($sql, $values = null)
214
    {
215
        return static::query($sql, $values)->fetch();
216
    }
217
}
218