-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.php
119 lines (109 loc) · 2.97 KB
/
api.php
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
<?php
require_once(__DIR__ . '/core/selectposts.php');
function main() {
$method = $_SERVER["REQUEST_METHOD"];
$id = $_GET['id'];
switch ($method) {
case 'POST':
$response = create();
break;
case 'GET':
if ($id) {
$response = read($id);
} else {
$response = readAll();
};
break;
case 'PUT':
$response = update($id);
break;
case 'DELETE':
$response = delete($id);
break;
default:
$response = notFound();
break;
}
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE");
header($response['status_code_header']);
if ($response['body']) {
echo $response['body'];
}
}
function readAll()
{
$db = new ListaPosts;
$response = [];
$result = $db->selectAll();
// var_dump($result);
$response['status_code_header'] = 'HTTP/1.1 200 OK';
$response['body'] = json_encode($result);
return $response;
}
function read($id)
{
$db = new ListaPosts;
$result = $db->selectById($id);
if (! $result) {
return notFound();
}
$response['status_code_header'] = http_response_code(200);
$response['body'] = json_encode($result);
return $response;
}
function create()
{
$db = new ListaPosts;
$input = (array) json_decode(file_get_contents('php://input'), TRUE);
$result = $db->insert($input);
if ( $result["success"] === true && $post = $db->selectById($result["id"]) ) {
return [
"status_code" => http_response_code(201),
"body" => json_encode($post),
];
} else {
$msg = $result["error"] ? [ "message" => $result["error"] ] : "";
return [
"status_code" => http_response_code(400),
"body" => json_encode($msg),
];
}
}
function update($id)
{
$db = new ListaPosts;
$input = (array) json_decode(file_get_contents('php://input'), TRUE);
$result = $db->update($id, $input);
if ( $result["success"] === true ) {
return [
"status_code" => http_response_code(200),
"body" => json_encode( $result["post"] ),
];
} else {
$msg = $result["error"] ? [ "message" => $result["error"] ] : "";
return [
"status_code" => http_response_code(400),
"body" => json_encode($msg),
];
}
}
function delete($id)
{
$db = new ListaPosts;
$result = $db->selectById($id);
if (! $result) {
return notFound();
}
$db->deleteById($id);
$response['status_code'] = http_response_code(204);
$response['body'] = json_encode(['message' => 'Deleted' ]);
return $response;
}
function notFound()
{
$response['status_code'] = http_response_code(404);
$response['body'] = json_encode(['message' => 'Not Found' ]);
return $response;
}
main();