Completed
Push — master ( 9bd8a0...c20901 )
by joanhey
01:43
created

LiteRecord::callback()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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