-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPostController.php
94 lines (78 loc) · 2.3 KB
/
PostController.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
<?php
require_once __DIR__ . '/../models/PostModel.php';
require_once __DIR__ . '/../entities/Post.php';
require_once __DIR__ . '/../util/Response.php';
class PostController
{
private PostModel $post_model;
public function __construct()
{
$this->post_model = new PostModel();
}
public function findAll()
{
$posts[] = new Post();
$posts = $this->post_model->findAll();
if ($posts) {
return json_encode($posts);
} else {
return Response::sendWithCode(400, "no results found");
}
}
public function findById($id)
{
$post = $this->post_model->findById($id);
if ($post->getId()) {
return $post->toJson();
} else {
return Response::sendWithCode(400, "no results found");
}
}
public function findByTitle($title)
{
$posts[] = new Post();
$posts = $this->post_model->findByTitle($title);
if ($posts) {
return json_encode($posts);
} else {
return Response::sendWithCode(400, "no results found");
}
}
public function create($data)
{
$post = new Post();
$post->setCategory($data->category);
$post->setTitle($data->title);
$post->setBody($data->body);
$post->setAuthor($data->author);
if ($this->post_model->create($post)) {
return Response::sendWithCode(201, "new post created");
} else {
return Response::sendWithCode(500, "an error");
}
}
public function update($id, $data)
{
$post = new Post();
$post->setId($id);
$post->setCategory($data->category);
$post->setTitle($data->title);
$post->setBody($data->body);
$post->setAuthor($data->author);
if ($this->post_model->update($post)) {
return Response::sendWithCode(200, "post updated");
} else {
return Response::sendWithCode(500, "an error");
}
}
public function delete($data)
{
$post = new Post();
$post->setId($data->id);
if ($this->post_model->delete($post)) {
return Response::sendWithCode(204, "deleted");
} else {
return Response::sendWithCode(500, "an error");
}
}
}