-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
94 lines (79 loc) · 2.85 KB
/
api.php
File metadata and controls
94 lines (79 loc) · 2.85 KB
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
<?php
require_once 'db.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT');
header('Access-Control-Allow-Headers: Content-Type');
$db = new Database();
function validateProduct($data) {
$errors = [];
if (empty($data['nom'])) {
$errors[] = "Le nom est requis";
}
if (!is_numeric($data['prix']) || $data['prix'] < 0) {
$errors[] = "Le prix doit être un nombre positif";
}
if (!is_numeric($data['stock']) || $data['stock'] < 0) {
$errors[] = "Le stock doit être un nombre positif";
}
return $errors;
}
try {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['action'])) {
throw new Exception('Action non spécifiée');
}
switch ($data['action']) {
case 'add':
$errors = validateProduct($data);
if (!empty($errors)) {
echo json_encode(['success' => false, 'errors' => $errors]);
exit;
}
$result = $db->addProduct(
$data['nom'],
$data['description'],
$data['prix'],
$data['stock']
);
echo json_encode(['success' => true, 'id' => $result]);
break;
case 'update':
$errors = validateProduct($data);
if (!empty($errors)) {
echo json_encode(['success' => false, 'errors' => $errors]);
exit;
}
$result = $db->updateProduct(
$data['id'],
$data['nom'],
$data['description'],
$data['prix'],
$data['stock']
);
echo json_encode(['success' => true]);
break;
case 'delete':
$result = $db->deleteProduct($data['id']);
echo json_encode(['success' => true]);
break;
case 'search':
$results = $db->searchProducts($data['term']);
echo json_encode($results);
break;
case 'filter':
$results = $db->filterByStock($data['minStock']);
echo json_encode($results);
break;
default:
throw new Exception('Action non reconnue');
}
} else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$products = $db->getAllProducts();
echo json_encode($products);
}
} catch (Exception $e) {
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
}