-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathController.php
More file actions
204 lines (184 loc) · 7.49 KB
/
Controller.php
File metadata and controls
204 lines (184 loc) · 7.49 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
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
<?php
class Controller {
private static $timezone = 'Europe/Copenhagen';
private static $timestamp;
// A separate array for transferring the metadata associated with the dataset.
private static $info = [
'Application used' => 'REST API (CRUD) at the GitHub Repository: https://github.com/brp-labs/rest-api',
'Dataset created' => null,
'Number of posts in dataset' => null
];
private static $keys = ['id', 'user_id', 'username', 'email', 'entity', 'entitycode'];
private static $requiredKeys = ['username', 'email'];
private static $uniqueKeys = ['user_id', 'username', 'email'];
private $model; // class instance
// Constructor
public function __construct($db) {
$this->model = new Model($db);
}
// Create a timestamp to be used in the header when returning a dataset
private static function getCurrentTimestamp() {
$timezone = new DateTimeZone(self::$timezone);
self::$timestamp = (new DateTime('now', $timezone))->format('Y-m-d H:i:s');
self::$info['Dataset created'] = self::$timestamp;
}
// Validate uniqueness of content (value) of unique keys
private function validateUniqueKeys($data) {
foreach(self::$uniqueKeys as $uniqueKey) {
if (array_key_exists($uniqueKey, $data)) {
$isUnique = $this->model->isKeyValueUnique($uniqueKey, $data[$uniqueKey]);
if (!$isUnique) {
http_response_code(412); // Precondition Failed
echo json_encode(["Message" => "A post already exists with the value of '$data[$uniqueKey]' at key '$uniqueKey'. Please use a different value for this unique key."]);
return false;
}
}
}
return true; // $isUnique is true
}
// Validate existens of required keys with content
private function validateRequiredKeys($data) {
foreach(self::$requiredKeys as $key) {
if (!array_key_exists($key, $data) || empty($data[$key])) {
return false;
}
}
return true;
}
// Sanitize
private static function sanitize($string) {
return htmlspecialchars(strip_tags(trim($string)));
}
// Create a post
public function create($data) {
if ($data) {
$keysValidated = self::validateRequiredKeys($data); // Required keys
if ($keysValidated) {
$keysValidated = self::validateUniqueKeys($data); // Unique keys
if ($keysValidated) {
$createdData = [];
foreach (self::$keys as $key) {
$createdData[$key] = isset($data[$key]) ? self::sanitize($data[$key]) : '';
}
extract($createdData, EXTR_OVERWRITE);
$result = $this->model->create($entitycode, $entity, $user_id, $username, $email);
if ($result) {
http_response_code(201); // Created
echo json_encode(['Message' => 'Post created successfully.']);
} else {
echo json_encode(['Message' => 'Post creation failed.']);
}
}
} else {
echo json_encode(["Message" => "Missing required keys with content. Required keys are: ".implode(", ", self::$requiredKeys)]);
}
} else {
http_response_code(400); // Bad Request
echo json_encode(["Message" => "No data submitted"]);
}
}
// Read a single post
public function read_single($id) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
$result = $this->model->read_single($id);
$rowCount = $result->rowCount();
if ($rowCount > 0) {
self::$info['Number of posts in dataset'] = $rowCount;
self::getCurrentTimestamp();
$post['Info'] = self::$info;
$post['Data'] = $result->fetch(PDO::FETCH_ASSOC);
http_response_code(200); // OK
// Check if read_single is called from within the current class
if (isset($backtrace[1]['class']) && $backtrace[1]['class'] === __CLASS__) {
return $post; // Id est: Return to the update-method
}
echo json_encode($post);
} else {
http_response_code(404); // Not Found
echo json_encode(["Message" => "No post found with the specified identifier (id-key)."]);
}
return false;
}
// Read all posts
public function read_all() {
$result = $this->model->read_all();
$rowCount = $result->rowCount();
if ($rowCount > 0) {
self::$info['Number of posts in dataset'] = $rowCount;
self::getCurrentTimestamp();
$posts['Info'] = self::$info;
$posts['Data'] = [];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($posts['Data'], $row);
}
http_response_code(200); // OK
echo json_encode($posts);
} else {
http_response_code(404); // Not Found
echo json_encode(["Message" => "No posts found."]);
}
}
// Search for posts
public function search($search) {
$search = self::sanitize($search);
$result = $this->model->search($search);
$rowCount = $result->rowCount();
if ($rowCount > 0) {
self::$info['Number of posts in dataset'] = $rowCount;
self::getCurrentTimestamp();
$posts['Info'] = self::$info;
$posts['Data'] = [];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($posts['Data'], $row);
}
http_response_code(200); // OK
echo json_encode($posts);
} else {
http_response_code(404); // Not Found
echo json_encode(["Message:" => "No posts found."]);
}
}
// Update a post
public function update($data) {
if (isset($data['id'])) {
$existingPost = $this->read_single($data['id']); // Type: array
if ($existingPost) {
$existingPost = $existingPost['Data']; // Leave ['Info'] key behind
foreach (self::$requiredKeys as $key) {
if (isset($data[$key]) && empty($data[$key])) {
echo json_encode(["Message" => "Required keys must have content. Required keys are: ".implode(", ", self::$requiredKeys)]);
return false;
}
}
$updatedData = [];
foreach (self::$keys as $key) {
$updatedData[$key] = isset($data[$key]) ? self::sanitize($data[$key]) : $existingPost[$key];
}
extract($updatedData, EXTR_OVERWRITE);
$result = $this->model->update($id, $entitycode, $entity, $user_id, $username, $email);
if ($result) {
http_response_code(200); // OK
echo json_encode(['Message' => 'Post updated successfully.']);
} else {
http_response_code(412); // Precondition Failed
echo json_encode(['Message' => 'Post update failed. Unchanged data migth have been submitted.']);
}
}
} else {
http_response_code(400); // Bad Request
echo json_encode(['Message' => 'Missing required identifier: id (numeric)']);
}
}
// Delete a post
public function delete($id) {
$id = self::sanitize($id);
$result = $this->model->delete($id);
if ($result) {
http_response_code(200); // OK
echo json_encode(['Message' => 'Post deleted successfully.']);
} else {
http_response_code(404); // Not Found
echo json_encode(['Message' => 'Post deletion failed. Post with the specified identifier (id-key) might not exist.']);
}
}
} // end: class Controller