LiteRecord::save()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
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
abstract 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
     * @return self|false
32
     */
33
    public function __invoke($id)
34
    {
35
        return self::get($id);
36
    }
37
38
    /**
39
     * Invoca el callback.
40
     *
41
     * @param  string  $callback
42
     * 
43
     * @return null|false
44
     */
45
    protected function callback(string $callback)
46
    {
47
        if (\method_exists($this, $callback)) {
48
            return $this->$callback();
49
        }
50
    }
51
52
    /**
53
     * Crear registro.
54
     *
55
     * @param  array           $data
56
     * 
57
     * @throws \PDOException
58
     * @return bool
59
     */
60
    public function create(array $data = []): bool
61
    {
62
        $this->dump($data);
63
64
        // Callback antes de crear
65
        if ($this->callback('_beforeCreate') === \false) {
66
            return \false;
67
        }
68
69
        $sql = QueryGenerator::insert($this, $data);
70
71
        if ( ! self::prepare($sql)->execute($data)) {
72
            return \false;
73
        }
74
75
        // Verifica si la PK es autogenerada
76
        $pk = static::$pk;
77
        if ( ! isset($this->$pk)) {
78
            $this->$pk = QueryGenerator::query(
79
                static::getDriver(),
80
                'last_insert_id',
81
                self::dbh(),
82
                $pk,
83
                static::getTable(),
84
                static::getSchema()
85
            );
86
        }
87
        // Callback despues de crear
88
        $this->callback('_afterCreate');
89
90
        return \true;
91
    }
92
93
    /**
94
     * Actualizar registro.
95
     *
96
     * @param  array              $data
97
     * 
98
     * @throws \KumbiaException
99
     * @return bool
100
     */
101
    public function update(array $data = []): bool
102
    {
103
        $this->dump($data);
104
        // Callback antes de actualizar
105
        if ($this->callback('_beforeUpdate') === \false) {
106
            return \false;
107
        }
108
109
        $values = [];
110
        $sql    = QueryGenerator::update($this, $values);
111
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 = []): bool
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(): string
154
    {
155
        return $this->hasPK() ? 'update' : 'create';
156
    }
157
158
    /**
159
     * Eliminar registro por pk.
160
     *
161
     * @param  string    $pk valor para clave primaria
162
     * 
163
     * @return bool
164
     */
165
    public static function delete($pk): bool
166
    {
167
        $source  = static::getSource();
168
        $pkField = static::$pk;
169
        // use pdo->execute()
170
        return static::query("DELETE FROM $source WHERE $pkField = ?", [$pk])->rowCount() > 0;
171
    }
172
173
    /**
174
     * Buscar por clave primaria.
175
     *
176
     * @param  string       $pk valor para clave primaria
177
     * @param  string       $fields campos que se desean obtener separados por coma
178
     * 
179
     * @return self|false
180
     */
181
    public static function get($pk, $fields = '*')
182
    {
183
        $sql = "SELECT $fields FROM ".static::getSource().' WHERE '.static::$pk.' = ?';
184
185
        return static::query($sql, [$pk])->fetch();
186
    }
187
188
    /**
189
     * Obtiene todos los registros de la consulta sql.
190
     *
191
     * @param  string       $sql
192
     * @param  array        $values
193
     * 
194
     * @return static[]
195
     */
196
    public static function all(string $sql = '', array $values = []): array
197
    {
198
        if ( ! $sql) {
199
            $sql = 'SELECT * FROM '.static::getSource();
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  array        $values
210
     * 
211
     * @return static|false
212
     */
213
    public static function first(string $sql, array $values = [])//: static in php 8
214
    {
215
        return static::query($sql, $values)->fetch();
216
    }
217
}
218