1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
|
<?php
// src/model/Model.php
abstract class Model extends DB
{
protected $db; // instance de PDO
protected $table; // <= enfant
//~ protected function __construct() // pour appel avec parent::__construct()
//~ {}
// getters
public function getTable(): string
{
return $this->table;
}
public function getAll(): array // à améliorer pour ne pas renvoyer $db et $table
{
return get_object_vars($this); // retourne les propriétés de l'objet
}
// setters
public function setID(int $value = 0)
{
if($value === 0)
{
$this->ID = $this->db->lastInsertId(); // méthode de PDO, attention lastInsertId() ne gère pas la concurence
}
else
{
$this->ID = $value;
}
return $this;
}
public function setTable(string $value)
{
$this->table = $value;
return($this);
}
public function hydrate(array $data): bool // $data = tableau associatif en entrée: nom_du_champ => valeur
{
foreach($data as $key => $value)
{
// nom du setter
// nom_propriete => setPropriete
// on sépare les mots par des espaces, ucwords met la première lettre de chaque mot en majuscule, puis on supprime les espaces
$setter_name = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key))); // ucwords: première lettre de chaque mot en majuscule
if(method_exists($this, $setter_name))
{
$this->$setter_name($value);
}
else
{
echo "debug: la méthode $setter_name n'existe pas\n";
return false;
}
}
return true;
}
// cette fonction reçoit des données d'un tableau simple, permettant d'associer des champs de formulaires aux noms différents des champs de la BDD
// méthode lancée par des objets de type enfants
function hydrateFromForm(string $data_string, Object $Presta = NULL): bool // quand l'objet est $Details, on hydrate aussi $Presta
{
//~ $tableSize = count(StructTablesDB::$structureOfTables[$this->getTable()]); // int
if($data_string !== '')
{
$data_array = explode('|', $data_string); // array
$check = false;
switch($this->getTable())
{
case 'clients';
if($data_array[0] == '')
{
echo "debug: données insuffisantes, le nom du client doit au minimum être renseigné\n";
return false;
}
else
{
$check = $this->hydrate(['prenom_nom' => $data_array[0], 'code_client' => $data_array[1], 'adresse' => $data_array[2], 'code_postal' => $data_array[3], 'ville' => $data_array[4], 'telephone' => $data_array[5], 'courriel' => $data_array[6], 'apropos' => $data_array[7]]);
}
break;
case 'prestations'; // inutilisé
break;
case 'devis';
$check = $this->hydrate(['taches' => $data_array[0], 'total_main_d_oeuvre' => $data_array[1], 'pieces' => $data_array[2], 'total_pieces' => $data_array[3], 'deplacement' => $data_array[4], 'prix_devis' => $data_array[5], 'total_HT' => $data_array[6], 'delai_livraison' => $data_array[7], 'validite_devis' => $data_array[8]]);
break;
case 'factures';
if(count($data_array) === 11)
{
$check = $Presta->hydrate(['mode_paiement' => $data_array[10]]);
if($check)
{
$check = $this->hydrate(['taches' => $data_array[0], 'machine' => $data_array[1], 'OS' => $data_array[2], 'donnees' => $data_array[3], 'cles_licences' => $data_array[4], 'total_main_d_oeuvre' => $data_array[5], 'pieces' => $data_array[6], 'total_pieces' => $data_array[7], 'deplacement' => $data_array[8], 'total_HT' => $data_array[9]]);
}
}
elseif(count($data_array) === 5)
{
$check = $this->hydrate(['machine' => $data_array[1], 'OS' => $data_array[2], 'donnees' => $data_array[3], 'cles_licences' => $data_array[4]]);
}
else
{
echo "debug: le tableau \$data_array n'a pas la taille attendue.\n";
return false;
}
break;
case 'cesu';
$check = $Presta->hydrate(['mode_paiement' => $data_array[3]]);
if($check)
{
$check = $this->hydrate(['taches' => $data_array[0], 'duree_travail' => $data_array[1], 'salaire' => $data_array[2]]);
}
break;
case 'locations';
$check = $this->hydrate(['designation' => $data_array[0], 'modele_description' => $data_array[1], 'valeur' => $data_array[2], 'etat_des_lieux_debut' => $data_array[3], 'etat_des_lieux_fin' => $data_array[4], 'duree_location' => $data_array[5], 'loyer_mensuel' => $data_array[6], 'loyers_payes' => $data_array[7], 'caution' => $data_array[8]]);
break;
default: // inutilisé
echo "debug: table inconnue hydrateFromForm()";
return false;
}
return $check;
}
else
{
echo "debug: annulation lors du formulaire\n";
return false;
}
}
// exécuter le SQL
// les attributs correspondent aux ? dans les requêtes préparées
// ne pas surcharger la méthode PDO::query() qui n'est pas compatible
protected function execQuery(string $sql, array $attributes = null)
{
$this->db = parent::getInstance(); // connexion
if($attributes !== null) // requête préparée
{
//~ var_dump($sql);
//~ var_dump($attributes);
$query = $this->db->prepare($sql);
$query->execute($attributes);
return $query;
}
else // requête simple
{
return $this->db->query($sql);
}
}
// méthodes CRUD
// create INSERT
public function create() // = write
{
$fields = [];
$question_marks = []; // ?
$values = [];
//~ var_dump($this);
foreach($this as $field => $value)
{
//~ var_dump($field); var_dump($value);
// champs non renseignées et variables de l'objet qui ne sont pas des champs
// note: avec le !== (au lieu de !=) une valeur 0 est différente de null
if($value !== null && $field != 'db' && $field != 'table')
{
$value = $this->clean_for_bash($value); // pour la BDD
$this->$field = $value; // pour latex
$fields[] = $field; // push
$question_marks[] = '?';
$values[] = $value;
}
}
$field_list = implode(', ', $fields);
$question_mark_list = implode(', ', $question_marks);
// INSERT INTO annonces (titre, description, actif) VALUES (?, ?, ?)
return($this->execQuery('INSERT INTO ' . $this->table . ' (' . $field_list . ') VALUES (' . $question_mark_list . ')', $values));
}
// read SELECT
protected function readAll(): array // obtenir une table
{
return($this->execQuery('SELECT * FROM ' . $this->table)->fetchAll()); // fonctionne aussi sans le point virgule dans le SQL!!
}
public function findById() // obtenir une entrée grace à son ID
{
return($this->execQuery('SELECT * FROM ' . $this->table . ' WHERE id = ' . $this->ID)->fetch());
}
public function getDetailsByIdPresta()
{
if($this->table == 'prestations')
{
// à l'occaz, créer une classe NonVendue et rendre Prestations abstraite
echo 'erreur: ne pas appeler Model::getDetailsByIdPresta() si la table ciblée est "prestations".';
return 0;
}
else
{
return $this->execQuery('SELECT * FROM ' . $this->table . ' WHERE id_Presta = ' . $this->ID_presta)->fetch(); // type array
}
}
protected function find(array $criteria): array // obtenir une entrée avec un tableau associatif 'champ' => 'valeur'
{
$fields = [];
$values = [];
// change "'ID' => 2" en "'ID' = ?" et "2"
foreach($criteria as $field => $value)
{
$fields[] = "$field = ?"; // même chose que: $field . " = ?"
$values[] = $value;
}
$field_list = implode(' AND ', $fields); // créer une chaîne reliant les morceaux avec le morceau AND en paramètre: 'adresse = ? AND ID = ?'
// SELECT * FROM annonces WHERE actif = 1;
return($this->execQuery('SELECT * FROM ' . $this->table . ' WHERE ' . $field_list, $values)->fetchAll());
}
// update UPDATE
public function update()
{
$fields = [];
$values = [];
foreach($this as $field => $value)
{
if($value !== null && $field != 'db' && $field != 'table') // champs non renseignées et variables de l'objet qui ne sont pas des champs
{
$value = $this->clean_for_bash($value); // pour la BDD
$this->$field = $value; // pour latex
$fields[] = $field . ' = ?';
$values[] = $value;
}
}
$values[] = $this->ID; // cette syntaxe ajoute une valeur au tableau
$field_list = implode(', ', $fields);
// UPDATE annonces SET titre = ?, description = ?, actif = ? WHERE id = ?
return($this->execQuery('UPDATE ' . $this->table . ' SET ' . $field_list . ' WHERE id = ?', $values));
}
public function updateOneValue(string $field, $value)
{
return($this->execQuery('UPDATE ' . $this->table . ' SET ' . $field . ' = ? WHERE id = ?', [$value, $this->ID]));
}
// delete DELETE
protected function delete(int $id)
{
return($this->execQuery("DELETE FROM {$this->table} WHERE id = ?", [$id])); // double quotes "" pour insertion de variable, paramètre [$id] parce qu'on veut un tableau
}
private function clean_for_bash($value)
{
if(is_string($value) && $value != '')
{
do
{
$value = trim($value);
$value = preg_replace('#^-#','' , $value); // en bash une chaîne commençant par un tiret est un paramètre
} while($value[0] == ' '|| $value[0] == '-'); // chaîne commençant par un tiret puis un espace, ou même - - - - -
}
return $value;
}
static public function createTables()
{
static $first_time = true;
if($first_time) // fonction normallement appelée qu'une seule fois
{
foreach(StructTablesDB::$structureOfTables as $tableName => $oneTable)
{
$query = 'CREATE TABLE IF NOT EXISTS ' . $tableName . ' (';
foreach($oneTable as $key => $value)
{
$query .= $key . ' ' . $value . ', ';
}
$query .= 'PRIMARY KEY(ID AUTOINCREMENT));';
parent::getInstance()->exec($query);
}
$first_time = false;
}
else
{
echo "Model::createTables() a déjà été appelée et ne fera rien.\n";
}
}
}
|