Completed
Push — 1.0 ( 0c9f96...f5d42a )
by Vermeulen
01:58
created

Sql::create_id()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 3 Features 1
Metric Value
cc 3
eloc 12
c 4
b 3
f 1
nc 3
nop 2
dl 0
loc 24
rs 8.9713
1
<?php
2
/**
3
 * Classes en rapport avec les sgdb
4
 * @author Vermeulen Maxime <[email protected]>
5
 * @version 1.0
6
 */
7
8
namespace BFWSql;
9
10
use \Exception;
11
12
/**
13
 * Classe POO gérant la sgbd.
14
 * @package bfw-sql
15
 */
16
class Sql implements \BFWSqlInterface\ISql
17
{
18
    /**
19
     * @var $_kernel : L'instance du Kernel
20
     */
21
    protected $_kernel;
22
    
23
    /**
24
     * @var \PDO L'objet PDO
25
     */
26
    protected $PDO;
27
    
28
    /**
29
     * @var \BFWSql\SqlConnect L'objet SqlConnect
30
     */
31
    protected $SqlConnect;
32
    
33
    /**
34
     * @var string|null $modeleName Nom de la table si c'est un modele
35
     */
36
    protected $modeleName;
37
    
38
    /**
39
     * @var string $prefix Le préfix des tables
40
     */
41
    protected $prefix = '';
42
    
43
    /**
44
     * Accesseur get vers l'attribut $PDO
45
     * 
46
     * @return \PDO
47
     */
48
    public function getPDO()
49
    {
50
        return $this->PDO;
51
    }
52
    
53
    /**
54
     * Accesseur get vers l'attribut $SqlConnect
55
     * 
56
     * @return \BFWSql\SqlConnect
57
     */
58
    public function getSqlConnect()
59
    {
60
        return $this->SqlConnect;
61
    }
62
    
63
    /**
64
     * Accesseur get vers l'attribut $modeleName
65
     * 
66
     * @return string
67
     */
68
    public function getModeleName()
69
    {
70
        return $this->modeleName;
71
    }
72
    
73
    /**
74
     * Accesseur get vers l'attribut $prefix
75
     * 
76
     * @return string
77
     */
78
    public function getPrefix()
79
    {
80
        return $this->prefix;
81
    }
82
    
83
    /**
84
     * Constructeur de la classe.
85
     * 
86
     * @param Sql_connect|null $DB_connect (ref) (default: null) L'instance de la classe Sql_connect. Si elle n'est pas indiqué, elle sera créé.
87
     * 
88
     * @throws \Exception
89
     */
90
    public function __construct(&$DB_connect=null)
91
    {
92
        $this->_kernel = getKernel();
93
        
94
        if($DB_connect === null)
95
        {
96
            global $DB;
97
            $DB_connect = $DB;
98
        }
99
        
100
        $this->PDO = null;
101
        $this->SqlConnect = null;
102
        
103
        if(is_object($DB_connect))
104
        {
105
            $this->PDO = $DB_connect->getPDO();
106
            $this->SqlConnect = &$DB_connect;
107
        }
108
        else {throw new Exception('La variable vers la connexion à la bdd doit être un objet.');}
109
        
110
        global $bd_prefix;
111
        $this->prefix = $bd_prefix;
112
    }
113
    
114
    /**
115
     * Modifie le nom de la table sur laquelle on travail
116
     * 
117
     * @param string $name le nom de la table
118
     * 
119
     * @return string : Le nom réel de la table avec préfix s'il y en a un de défini.
120
     */
121
    public function set_modeleName($name)
122
    {
123
        $this->modeleName = $this->prefix.$name;
124
        return $this->modeleName;
125
    }
126
    
127
    /**
128
     * Renvoi l'id du dernier élément ajouté en bdd
129
     * 
130
     * @param string|null $name (default: null) nom de la séquence pour l'id (pour PostgreSQL par exemple)
131
     * 
132
     * @return integer
133
     */
134
    public function der_id($name=null)
135
    {
136
        return (int) $this->PDO->lastInsertId($name);
137
    }
138
    
139
    /**
140
     * Renvoi l'id du dernier élément ajouté en bdd pour une table sans Auto Incrément
141
     * 
142
     * @param string       $table   La table
143
     * @param string       $champID Le nom du champ correspondant à l'id
144
     * @param string|array $order   Les champs sur lesquels se baser
145
     * @param string|array $where   Clause where
146
     * 
147
     * @return integer le dernier id, 0 si aucun résultat
148
     */
149
    public function der_id_noAI($table, $champID, $order, $where='')
150
    {
151
        $req = $this->select()->from($table, $champID)->limit(1);
152
    
153
        if(is_array($where))
154
        {
155
            foreach($where as $val)
156
            {
157
                $req->where($val);
158
            }
159
        }
160
        elseif($where != '')
161
        {
162
            $req->where($where);
163
        }
164
        
165
        if(is_array($order))
166
        {
167
            foreach($order as $val)
168
            {
169
                $req->order($val);
170
            }
171
        }
172
        else
173
        {
174
            $req->order($order);
175
        }
176
        
177
        $res = $req->fetchRow();
178
        $req->closeCursor();
0 ignored issues
show
Bug introduced by
The method closeCursor() does not seem to exist on object<BFWSql\SqlSelect>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
179
        
180
        if($res)
181
        {
182
            return (int) $res[$champID];
183
        }
184
        
185
        return 0;
186
    }
187
    
188
    /**
189
     * Créer une instance de Sql_Select permettant de faire une requête de type SELECT
190
     * 
191
     * @param string $type (default: "array") Le type de retour pour les données. Valeurs possible : array|objet|object
192
     * 
193
     * @return \BFWSql\SqlSelect L'instance de l'objet Sql_Select créé
194
     */
195
    public function select($type='array')
196
    {
197
        return new SqlSelect($this, $type);
198
    }
199
    
200
    /**
201
     * Créer une instance de Sql_Insert permettant de faire une requête de type INSERT INTO
202
     * 
203
     * @param string $table  (default: null) La table sur laquelle agir
204
     * @param array  $champs (default: null) Les données à ajouter : array('champSql' => 'données');
205
     * 
206
     * @return \BFWSql\SqlInsert L'instance de l'objet Sql_Select créé
207
     */
208
    public function insert($table=null, $champs=null)
209
    {
210
        return new SqlInsert($this, $table, $champs);
0 ignored issues
show
Bug introduced by
It seems like $champs defined by parameter $champs on line 208 can also be of type null; however, BFWSql\SqlInsert::__construct() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
211
    }
212
    
213
    /**
214
     * Créer une instance de Sql_Update permettant de faire une requête de type UPDATE
215
     * 
216
     * @param string $table  (default: null) La table sur laquelle agir
217
     * @param array  $champs (default: null) Les données à ajouter : array('champSql' => 'données');
218
     * 
219
     * @return \BFWSql\SqlUpdate L'instance de l'objet Sql_Select créé
220
     */
221
    public function update($table=null, $champs=null)
222
    {
223
        return new SqlUpdate($this, $table, $champs);
0 ignored issues
show
Bug introduced by
It seems like $champs defined by parameter $champs on line 221 can also be of type null; however, BFWSql\SqlUpdate::__construct() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
224
    }
225
    
226
    /**
227
     * Créer une instance de Sql_Delete permettant de faire une requête de type DELETE FROM
228
     * 
229
     * @param string $table (default: null) La table sur laquelle agir
230
     * 
231
     * @return \BFWSql\SqlDelete L'instance de l'objet Sql_Select créé
232
     */
233
    public function delete($table=null)
234
    {
235
        return new SqlDelete($this, $table);
236
    }
237
    
238
    /**
239
     * Trouve le premier id libre pour une table et pour un champ
240
     * 
241
     * @param string $table La table
242
     * @param string $champ Le champ. Les valeurs du champ doivent être du type int.
243
     * 
244
     * @throws \Exception Si ue erreur dans la recherche d'id s'est produite
245
     * 
246
     * @return integer L'id libre trouvé. False si erreur
247
     */
248
    public function create_id($table, $champ)
249
    {
250
        $req = $this->select()->from($table, $champ)->order($champ.' ASC')->limit(1);
251
        $res = $req->fetchRow();
252
        $req->closeCursor();
0 ignored issues
show
Bug introduced by
The method closeCursor() does not seem to exist on object<BFWSql\SqlSelect>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
253
        
254
        if($res)
255
        {
256
            if($res[$champ] == 1)
257
            {
258
                $req2 = $this->select()->from($table, $champ)->order($champ.' DESC')->limit(1);
259
                $res2 = $req2->fetchRow();
260
                $req2->closeCursor();
0 ignored issues
show
Bug introduced by
The method closeCursor() does not seem to exist on object<BFWSql\SqlSelect>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
261
                
262
                //Exception levé si $res2 == false.
263
                return $res2[$champ]+1;
264
            }
265
            
266
            return $res[$champ]-1;
267
        }
268
        // Pas de else car exception levé.
269
        
270
        return 1;
271
    }
272
    
273
    /**
274
     * Execute la requête mise en paramètre
275
     * 
276
     * @param string $requete La requête à exécuter
277
     * 
278
     * @throws \Exception Si la requête à echoué
279
     * 
280
     * @return \PDOStatement La ressource de la requête exécuté si elle a réussi.
281
     */
282
    public function query($requete)
283
    {
284
        $this->upNbQuery();
285
        $req = $this->PDO->query($requete); //On exécute la reqête
286
        
287
        //On récupère l'erreur
288
        $erreur = $this->PDO->errorInfo();
289
        
290
        //On créé l'exception que s'il y a véritablement une erreur.
291
        if(!$req && $erreur[0] != null && $erreur[0] != '00000' && isset($erreur[2])) 
292
        {
293
            throw new Exception($erreur[2]);
294
        }
295
        
296
        //Si la requête à réussi, on retourne sa ressource
297
        return $req;
298
    }
299
    
300
    /**
301
     * Incrémente le nombre de requête effectué
302
     * 
303
     * @return void
304
     */
305
    public function upNbQuery()
306
    {
307
        $this->SqlConnect->upNbQuery();
308
    }
309
    
310
    /**
311
     * Accesseur pour accéder au nombre de requête
312
     * 
313
     * @return integer Le nombre de requête
314
     */
315
    public function getNbQuery()
316
    {
317
        return $this->SqlConnect->getNbQuery();
318
    }
319
}
320
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...