Completed
Push — master ( 1c9390...6ae3d1 )
by Alberto
01:48
created

LiteRecord::pk()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 4
rs 10
c 1
b 0
f 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 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(
80
                static::getDriver(),
81
                'last_insert_id',
82
                self::dbh(),
83
                $pk,
84
                static::getTable(),
85
                static::getSchema()
86
            );
87
        }
88
        // Callback despues de crear
89
        $this->callback('_afterCreate');
90
91
        return true;
92
    }
93
94
    /**
95
     * Actualizar registro.
96
     *
97
     * @param array $data
98
     *
99
     * @return bool
100
     */
101
    public function update(array $data = [])
102
    {
103
        $this->dump($data);
104
        // Callback antes de actualizar
105
        if ($this->callback('_beforeUpdate') === false) {
106
            return false;
107
        }
108
        $this->hasPK();
109
        $values = [];
110
        $sql = QueryGenerator::update($this, $values);
111
        //var_dump($values);var_dump($sql);die;
112
        if (!self::prepare($sql)->execute($values)) {
113
            return false;
114
        }
115
        // Callback despues de actualizar
116
        $this->callback('_afterUpdate');
117
118
        return true;
119
    }
120
121
    /**
122
     * Guardar registro.
123
     *
124
     * @param array $data
125
     *
126
     * @return bool
127
     */
128
    public function save(array $data = [])
129
    {
130
        $this->dump($data);
131
132
        if ($this->callback('_beforeSave') === false) {
133
            return false;
134
        }
135
136
        $method = $this->saveMethod();
137
        $result = $this->$method();
138
139
        if (!$result) {
140
            return false;
141
        }
142
143
        $this->callback('_afterSave');
144
145
        return true;
146
    }
147
148
    /**
149
     * Get the Primary Key value for the object
150
     * @return mixed
151
     */
152
    public function pk(){
153
        $pk = static::getPK();
154
        return empty($this->$pk) ? null : $this->$pk;
155
    }
156
157
    /**
158
     * Retorna el nombre del metodo a llamar durante un save (create o update).
159
     *
160
     * @return string
161
     */
162
    protected function saveMethod()
163
    {
164
        $pk = static::getPK();
165
166
        return (empty($this->$pk) || !static::exists($this->$pk)) ?
167
            'create' : 'update';
168
    }
169
170
    /**
171
     * Eliminar registro por pk.
172
     *
173
     * @param int $pk valor para clave primaria
174
     *
175
     * @return bool
176
     */
177 View Code Duplication
    public static function delete($pk)
0 ignored issues
show
Duplication introduced by manuel_j555
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...
178
    {
179
        $source = static::getSource();
180
        $pkField = static::getPK();
181
182
        return static::query("DELETE FROM $source WHERE $pkField = ?", (int) $pk)->rowCount() > 0;
183
    }
184
185
    /**
186
     * Buscar por clave primaria.
187
     *
188
     * @param string $pk     valor para clave primaria
189
     * @param string $fields campos que se desean obtener separados por coma
190
     *
191
     * @return LiteRecord
192
     */
193
    public static function get($pk, $fields = '*')
194
    {
195
        $source = static::getSource();
196
        $pkField = static::getPK();
197
198
        $sql = "SELECT $fields FROM $source WHERE $pkField = ?";
199
200
        return static::query($sql, $pk)->fetch();
201
    }
202
203
    /**
204
     * Obtiene todos los registros de la consulta sql.
205
     *
206
     * @param string         $sql
207
     * @param string | array $values
208
     *
209
     * @return array
210
     */
211
    public static function all($sql = '', $values = null)
212
    {
213
        if (!$sql) {
214
            $source = static::getSource();
215
            $sql = "SELECT * FROM $source";
216
        }
217
218
        return static::query($sql, $values)->fetchAll();
219
    }
220
221
    /**
222
     * Obtiene el primer registro de la consulta sql.
223
     *
224
     * @param string         $sql
225
     * @param string | array $values
226
     *
227
     * @return array
228
     */
229
    public static function first($sql, $values = null)
230
    {
231
        return static::query($sql, $values)->fetch();
232
    }
233
}
234