Passed
Push — master ( 8851e6...60b502 )
by Anthony
02:56
created

Database::insert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
	namespace core;
3
4
	use core\HTML\flashmessage\FlashMessage;
5
	use PDO;
6
7
	class Database {
8
		private $db_type;
9
		private $db_name;
10
		private $db_user;
11
		private $db_pass;
12
		private $db_host;
13
		private $dbc;
14
15
		//pour le query builder
16
		private $req_beginning;
17
		private $champs = [];
18
		private $value = [];
19
		private $conditions = [];
20
		private $table = [];
21
22
23
24
		//-------------------------- CONSTRUCTEUR ----------------------------------------------------------------------------//
25
		public function __construct($db_type, $db_name, $db_user, $db_pass, $db_host) {
26
			$this->db_type = $db_type;
27
			$this->db_name = $db_name;
28
			$this->db_user = $db_user;
29
			$this->db_pass = $db_pass;
30
			$this->db_host = $db_host;
31
		}
32
		//-------------------------- FIN CONSTRUCTEUR ----------------------------------------------------------------------------//
33
34
35
36
		//-------------------------- GETTER ----------------------------------------------------------------------------//
37
		/**
38
		 * function qui fait la connexion a la bdd ne peu etre appelee que dans la classe
39
		 * @return PDO
40
		 */
41
		private function getPdo() {
42
			if ($this->dbc === null) {
43
				$dbc = new PDO($this->db_type.':host='.$this->db_host.';dbname='.$this->db_name, $this->db_user, $this->db_pass);
44
				$dbc->exec("set names utf8");
45
				$this->dbc = $dbc;
46
			}
47
			return $this->dbc;
48
		}
49
		//-------------------------- FIN GETTER ----------------------------------------------------------------------------//
50
51
		//-------------------------- FUNCTION QUI FONT DES REQUETES SUR LA BDD --------------------------------------------//
52
		/**
53
		 * effectue une requete en selectr dans la BDD, si ok on renvoit les donnees sinon on renvoi une erreur
54
		 * @param $req
55
		 * @return array
56
		 */
57
		public function query($req) {
58
			$query = $this->getPdo()->query($req);
59
60
			if ($query) {
61
				$obj = $query->fetchAll(PDO::FETCH_OBJ);
62
				return $obj;
63
			}
64
			else {
65
				FlashMessage::setFlash("Une erreur est survenue en executant cette requette : ".$req);
66
			}
67
		}
68
69
		/**
70
		 * fonction qui prepare une requete et qui l'envoi, marche pour insert et update et delete
71
		 * @param $req -> la req a executer
72
		 * @param $value -> le ou les tableaux de valeurs
73
		 */
74
		public function prepare($req, $value) {
75
			$query = $this->getPdo()->prepare($req);
76
			//si on a plusieurs tableaux
77
			if (array_key_exists(0, $value)) {
78
				foreach ($value as $val) {
79
					if (!$query->execute($val)) {
80
						$err = true;
81
					}
82
				}
83
			}
84
			else {
85
				if (!$query->execute($value)) {
86
					$err = true;
87
				}
88
			}
89
90
			//si on a une erreur on renvoi un message
91
			if (isset($err)) {
92
				FlashMessage::setFlash("Une erreur est survenue en executant cette requette : ".$req);
93
			}
94
		}
95
96
		/**
97
		 * pour savoir si une valeur sur un champ précis existe deja en bdd, renvoi true si vrai
98
		 * @param $table
99
		 * @param $champ
100
		 * @param $value
101
		 * @return boolean|null
102
		 */
103
		public function rechercherEgalite($table, $champ, $value, $id_table = null, $id = null) {
104
			if ($id == null) {
105
				$query = $this->getPdo()->query("SELECT COUNT($champ) as nb FROM $table WHERE $champ LIKE '$value'");
106
			}
107
			else {
108
				$query = $this->getPdo()->query("SELECT COUNT($champ) as nb FROM $table WHERE $champ LIKE '$value' AND $id_table != $id");
109
			}
110
111
			if (count($query) > 0) {
112
				foreach ($query as $obj) {
113
					$nb = $obj["nb"];
114
				}
115
116
				if ((isset($nb)) && ($nb != 0)) return true;
117
			}
118
			else {
119
				return false;
120
			}
121
		}
122
		//-------------------------- FIN FUNCTION QUI FONT DES REQUETES SUR LA BDD --------------------------------------------//
123
124
125
		/**
126
		 * tester si une table dans la base donnee existe
127
		 * @param string $table definit la table pour laquelle on doit tester l'existance
128
		 * @return boolean
129
		 */
130
		public function TestTableExist($table) {
131
			$query = $this->getPdo()->query("SHOW TABLES LIKE '$table'");
132
133
			if ($query->rowCount() > 0) {
134
				return true;
135
			}
136
			else {
137
				return false;
138
			}
139
		}
140
141
		public function quote($quote) {
142
			return $this->getPdo()->quote($quote);
143
		}
144
145
		public function lastInsertId() {
146
			return $this->getPdo()->lastInsertId();
147
		}
148
149
150
151
		//-------------------------- QUERY BUILDER in construction no test have been done --------------------------------------------//
152
		/**
153
		 * @param string $champs
154
		 * @return $this
155
		 *
156
		 * pour initialisé une requete avec un select
157
		 */
158
		public function select($champs = "*") {
159
			$this->req_beginning = "SELECT ";
160
			$this->champs[] = $champs;
161
162
			return $this;
163
		}
164
165
		/**
166
		 * @param $champ
167
		 * @param $value
168
		 * @return $this
169
		 *
170
		 * fonction qui permet de préparer les champs et la valeur qui y sera associée
171
		 */
172
		public function insert($champ, $value) {
173
			$this->add($champ, $value);
174
175
			$this->req_beginning = "INSERT INTO ";
176
177
			return $this;
178
		}
179
180
		/**
181
		 * @param $champ
182
		 * @param $value
183
		 * @return $this
184
		 */
185
		public function update($champ, $value) {
186
			$this->add($champ, $value);
187
188
			$this->req_beginning = "UPDATE ";
189
190
			return $this;
191
		}
192
193
		/**
194
		 * @return $this
195
		 *
196
		 * fonction qui initialise un delete en base de donnée
197
		 */
198
		public function delete() {
199
			$this->req_beginning = "DELETE FROM ";
200
201
			return $this;
202
		}
203
204
		/**
205
		 * @param $champ
206
		 * @param $value
207
		 *
208
		 * fonction qui se cahrge d'ajouter les valeurs et les champs si non null dans leurs
209
		 * tableaux respectifs (appellée dans this->insert et this->update
210
		 */
211
		private function add($champ, $value) {
212
			if (($champ !== null) && ($value !== null)) {
213
				$this->champs[] = $champ;
214
				$this->value[] = $value;
215
			}
216
		}
217
218
		/**
219
		 * @param $table
220
		 * @return $this
221
		 *
222
		 * pour initialiser la les listes des tables ou il faudra aler chercher les données
223
		 */
224
		public function from($table) {
225
			$this->table[] = $table;
226
227
			return $this;
228
		}
229
230
		/**
231
		 * @param $table
232
		 *
233
		 * pour initialiser la table dans laquelle on va insérer les données
234
		 */
235
		public function into($table) {
236
			$this->table[] = $table;
237
238
			return $this;
239
		}
240
241
		/**
242
		 * @param $champ
243
		 * @param $cond
244
		 * @param $champ_test
245
		 * @param null $closure
246
		 * @return $this
247
		 *
248
		 * pour intialiser la ou les clauses where d'une requete
249
		 */
250
		public function where($champ, $cond, $champ_test, $closure = null) {
251
			if ( $closure === null) {
252
				$this->conditions[] = $champ.$cond.$champ_test;
253
			}
254
			else {
255
				$this->conditions[] = $champ.$cond.$champ_test." ".$closure;
256
			}
257
258
			return $this;
259
		}
260
261
		/**
262
		 * @return array
263
		 *
264
		 * fonction qui permet de récupérer un select fait sur une table
265
		 */
266
		public function get() {
267
			$requete = $this->req_beginning . implode(",", $this->champs) . " FROM " . implode(",", $this->table);
268
269
			if ($this->conditions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->conditions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
270
				$requete .= " WHERE ". implode(" ", $this->conditions);
271
			}
272
273
			$this->unsetQueryBuilder();
274
			return $this->query($requete);
275
		}
276
277
		/**
278
		 * fonction utlisée pour terminer un insert ou un update dans la base de données
279
		 */
280
		public function set() {
281
			$values = array_combine($this->champs, $this->value);
282
283
			$datas = [];
284
			for ($i=0 ; $i<count($this->champs) ; $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
285
				$datas[] = $this->champs[$i]."=:".$this->champs[$i];
286
			}
287
288
			//si on a des conditions alors on sera dans un insert
289
			$requete = $this->req_beginning . implode(",", $this->table) . " SET " . implode(", ", $datas);
290
291
			if ($this->conditions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->conditions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
292
				$requete .= " WHERE " . implode(" ", $this->conditions);
293
			}
294
295
			$this->prepare($requete, $values);
296
			$this->unsetQueryBuilder();
297
		}
298
299
		/**
300
		 * fonction utilisée pour finir un delete
301
		 */
302
		public function del() {
303
			$requete = $this->req_beginning . implode(",", $this->table);
304
305
			if ($this->conditions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->conditions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
306
				$requete .= " WHERE " . implode(" ", $this->conditions);
307
			}
308
309
			$this->query($requete);
310
			$this->unsetQueryBuilder();
311
		}
312
313
		/**
314
		 * fonction qui détruit toutes les variables utilisées.
315
		 */
316
		private function unsetQueryBuilder() {
317
			$this->req_beginning;
318
			$this->champs = [];
319
			$this->value = [];
320
			$this->conditions = [];
321
			$this->table = "";
0 ignored issues
show
Documentation Bug introduced by
It seems like '' of type string is incompatible with the declared type array of property $table.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
322
		}
323
	}