Completed
Push — master ( 3be506...1c2175 )
by joanhey
01:57
created

lib/Kumbia/ActiveRecord/LiteRecord.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
     * Retorna el nombre del metodo a llamar durante un save (create o update).
150
     *
151
     * @return string
152
     */
153
    protected function saveMethod()
154
    {
155
        $pk = static::getPK();
156
157
        return (empty($this->$pk) || !static::exists($this->$pk)) ?
158
            'create' : 'update';
159
    }
160
161
    /**
162
     * Eliminar registro por pk.
163
     *
164
     * @param int $pk valor para clave primaria
165
     *
166
     * @return bool
167
     */
168 View Code Duplication
    public static function delete($pk)
0 ignored issues
show
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...
169
    {
170
        $source = static::getSource();
171
        $pkField = static::getPK();
172
173
        return static::query("DELETE FROM $source WHERE $pkField = ?", (int) $pk)->rowCount() > 0;
174
    }
175
176
    /**
177
     * Buscar por clave primaria.
178
     *
179
     * @param string $pk     valor para clave primaria
180
     * @param string $fields campos que se desean obtener separados por coma
181
     *
182
     * @return LiteRecord
183
     */
184
    public static function get($pk, $fields = '*')
185
    {
186
        $source = static::getSource();
187
        $pkField = static::getPK();
188
189
        $sql = "SELECT $fields FROM $source WHERE $pkField = ?";
190
191
        return static::query($sql, $pk)->fetch();
192
    }
193
194
    /**
195
     * Obtiene todos los registros de la consulta sql.
196
     *
197
     * @param string         $sql
198
     * @param string | array $values
199
     *
200
     * @return array
201
     */
202
    public static function all($sql = '', $values = null)
203
    {
204
        if (!$sql) {
205
            $source = static::getSource();
206
            $sql = "SELECT * FROM $source";
207
        }
208
209
        return static::query($sql, $values)->fetchAll();
210
    }
211
212
    /**
213
     * Obtiene el primer registro de la consulta sql.
214
     *
215
     * @param string         $sql
216
     * @param string | array $values
217
     *
218
     * @return array
219
     */
220
    public static function first($sql, $values = null)
221
    {
222
        return static::query($sql, $values)->fetch();
223
    }
224
}
225