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
<?php
class UsersController {
private $requestMethod;
private $params;
public function __construct($requestMethod, $params=null)
{
$this->requestMethod = $requestMethod;
$this->params = $params;
}
public function processRequest()
{
switch ($this->requestMethod) {
case 'GET':
if (isset($this->params)) {
$response = $this->getUserById(($this->params)[0]);
}else{
$response = $this->getAllUsers();
}
break;
case 'POST':
$response = $this->createUser($_POST['name'], $_POST['email']);
break;
case 'DELETE':
if (isset($this->params)) {
$response = $this->deleteUser(($this->params)[0]);
}
break;
case 'PUT':
if (isset($this->params)) {
$response = $this->editUser(($this->params)[0], ($this->params)[1], ($this->params)[2]);
}
break;
default:
$response = $this->notFoundResponse();
break;
}
header($response['status_code_header']);
if ($response['body']) {
echo $response['body'];
}
}
private function createUser($name, $email)
{
$user = UserModel::createUser($name, $email);
$response =[];
$response['status_code_header']=http_response_code(200);
$response['body'] = "User created";
return $response;
}
private function editUser($id, $name, $email)
{
$user = UserModel::editUser($id, $name, $email);
$response =[];
$response['status_code_header']=http_response_code(200);
$response['body'] = "User updated";
return $response;
}
private function deleteUser($id)
{
$user = UserModel::deleteUser($id);
$response =[];
$response['status_code_header']=http_response_code(200);
$response['body'] = "User deleted";
return $response;
}
private function getUserById($id)
{
$user = UserModel::getUserById($id);
$response =[];
$response['status_code_header']=http_response_code(200);
$response['body'] = json_encode($user);
return $response;
}
private function getAllUsers()
{
$users = UserModel::getAllUsers();
$response =[];
$response['status_code_header']=http_response_code(200);
$response['body'] = json_encode($users);
return $response;
}
private function notFoundResponse()
{
$response['status_code_header'] = 'HTTP/1.1 404 Not Found';
$response['body'] = null;
return $response;
}
}