Post::modify()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controllers\Admin;
4
5
use App\Models\CategoryModel;
6
use App\Models\CommentModel;
7
use App\Models\PostModel;
8
use App\Models\TagModel;
9
use Core\AdminController;
10
use Core\Constant;
11
use Core\Container;
12
13
class Post extends AdminController
14
{
15
16
    protected $siteConfig;
17
    protected $pagination;
18
19
    private $categoryModel;
20
    private $tagModel;
21
    private $postModel;
22
    private $commentModel;
23
24
    public function __construct(Container $container)
25
    {
26
        $this->loadModules[] = 'SiteConfig';
27
        $this->loadModules[] = 'pagination';
28
        parent::__construct($container);
29
30
        $this->categoryModel = new CategoryModel($this->container);
31
        $this->tagModel = new TagModel($this->container);
32
        $this->postModel = new PostModel($this->container);
33
        $this->commentModel = new CommentModel($container);
34
35
        //adding the necessary default data
36
        $this->data['configs'] = $this->siteConfig->getSiteConfig();
37
        $this->data['categories'] = $this->categoryModel->getCategories();
38
        $this->data["pendingCommentsCount"] = $this->commentModel->countPendingComments();
39
    }
40
41
    /**
42
     * add tags to a post
43
     * @param array $tags list of tags to apply
44
     * @param int $postId the post to add tags to
45
     * @throws \Exception
46
     */
47
    private function addTags(array $tags, int $postId): void
48
    {
49
        foreach ($tags as $tag) {
50
            if (isset($tag["id"])) {
51
                $this->tagModel->addTagToPost($postId, $tag["id"]);
52
                continue;
53
            }
54
            $this->tagModel->addNewTagToPost($postId, $tag["name"]);
55
        }
56
    }
57
58
    /**
59
     * page for new post
60
     */
61
    public function new()
62
    {
63
        $this->onlyAdmin();
64
        $this->data['tags'] = $this->tagModel->getTags();
65
        $this->renderView('Admin/Post');
66
    }
67
68
    /**
69
     * Lists all the posts
70
     * @param string $page
71
     * @param int $postsPerPage
72
     * @throws \ReflectionException
73
     * @throws \Twig_Error_Loader
74
     * @throws \Twig_Error_Runtime
75
     * @throws \Twig_Error_Syntax
76
     */
77
    public function list(string $page = "page-1", int $postsPerPage = Constant::LIST_PER_PAGE)
78
    {
79
        $this->onlyAdmin();
80
81
        $totalPosts = $this->postModel->totalNumberFullPosts();
82
        $pagination = $this->pagination->getPagination($page, $totalPosts, $postsPerPage);
83
84
        if ($postsPerPage !== Constant::LIST_PER_PAGE) {
85
            $this->data['paginationPostsPerPage'] = $postsPerPage;
86
        }
87
88
        $this->data["posts"] = $this->postModel->getFullPosts($pagination["offset"], $postsPerPage);
89
        $this->data['pagination'] = $pagination;
90
        $this->renderView("Admin/ListPost");
91
    }
92
93
    /**
94
     * Shows the post to modify and update
95
     * @throws \ReflectionException
96
     * @throws \Twig_Error_Loader
97
     * @throws \Twig_Error_Runtime
98
     * @throws \Twig_Error_Syntax
99
     * @throws \ErrorException
100
     */
101
    public function modify(string $slug): void
102
    {
103
        $this->onlyAdmin();
104
105
        $postId = $this->postModel->getPostIdFromSlug($slug);
106
107
        $this->data['post'] = $this->postModel->getSinglePost($postId);
108
        $this->data['postTags'] = $this->tagModel->getTagsOnPost($postId);
109
        $this->data['tags'] = $this->tagModel->getTags();
110
        $this->renderView('Admin/Post');
111
    }
112
113
    /**
114
     * Create a new post
115
     * @throws \Exception
116
     */
117
    public function createNewPost()
118
    {
119
        //Security checks
120
        $this->onlyAdmin();
121
        $this->onlyPost();
122
123
        $posts = $this->request->getDataFull();
124
        $userSessionId = (int)$this->session->get("userId");
125
126
127
        $title = trim($posts["postTitle"]);
128
        $postImage = $posts["postImage"];
129
        $postSlug = trim($posts["postSlug"]);
130
        $article = $posts["postTextArea"];
131
        $idCategory = $posts["categorySelector"];
132
        $published = $posts["isPublished"];
133
        $onFrontPage = $posts["isOnFrontPage"];
134
        $idUser = $userSessionId;
135
136
        if (!is_int($idUser) || $idUser === null) {
137
            throw new \Error("Invalid userID");
138
        }
139
140
        //security and error checks
141
        $error = false;
142
        if ($title == "") {
143
            $error = true;
144
            $this->alertBox->setAlert("empty title not allowed", "error");
145
        }
146
        if ($postSlug == "") {
147
            $error = true;
148
            $this->alertBox->setAlert("empty slug not allowed", "error");
149
        }
150
        if (!$this->postModel->isPostSlugUnique($postSlug)) {
151
            $error = true;
152
            $this->alertBox->setAlert("Slug not unique", "error");
153
        }
154
155
        if ($error) {
156
            $this->container->getResponse()->redirect("admin/post/new");
157
        }
158
159
        $postId = $this->postModel->newPost($title, $postImage, $idCategory, $article, $idUser, $published,
160
            $onFrontPage,
161
            $postSlug);
162
163
        //Taking care of tags.
164
        if (isset($posts["tags"])) {
165
            $this->addTags($posts["tags"], $postId);
166
        }
167
168
        //checking result and redirecting
169
        if ($postId != null) {
170
            $this->alertBox->setAlert("Post " . $title . " Created");
171
            $this->container->getResponse()->redirect("admin/post/modify/" . $postSlug);
172
        }
173
        $this->alertBox->setAlert("Error creating " . $title, "error");
174
        $this->container->getResponse()->redirect("admin/post/new");
175
176
    }
177
178
    /**
179
     * update a post
180
     * @throws \Exception
181
     */
182
    public function modifyPost()
183
    {
184
        //Security checks
185
        $this->onlyAdmin();
186
        $this->onlyPost();
187
188
        $posts = $this->container->getRequest()->getDataFull();
189
190
        $postId = $posts["postId"];
191
        $title = trim($posts["postTitle"]);
192
        $postImage = $posts["postImage"];
193
        $postSlug = trim($posts["postSlug"]);
194
        $article = $posts["postTextArea"];
195
        $idCategory = $posts["categorySelector"];
196
        $published = $posts["isPublished"];
197
        $onFrontPage = $posts["isOnFrontPage"];
198
199
        //security and error checks
200
        $originalPostSlug = $this->postModel->getpostSlugFromId($postId);
201
        $error = false;
202
        if ($title == "") {
203
            $error = true;
204
            $this->alertBox->setAlert("empty title not allowed", "error");
205
        }
206
207
        if ($postSlug == "") {
208
            $error = true;
209
            $this->alertBox->setAlert("empty slug not allowed", "error");
210
        }
211
212
        if ($postSlug != $originalPostSlug) //if the slug has been updated
213
        {
214
            if (!$this->postModel->isPostSlugUnique($postSlug)) {
215
                $error = true;
216
                $originalPostSlug = $this->postModel->getPostSlugFromId($postId);
217
                $this->alertBox->setAlert("Slug not unique", "error");
218
            }
219
        }
220
        if ($error) {
221
            $this->container->getResponse()->redirect("admin/post/modify/$originalPostSlug");
222
        }
223
224
        //Update the post
225
        $postUpdate = $this->postModel->modifyPost($postId, $title, $postImage, $idCategory, $article, $published,
226
            $onFrontPage, $postSlug);
227
228
        // Tags
229
        //remove all tags
230
        $this->tagModel->removeTagsOnPost($postId);
231
        //set new tags
232
        if (isset($posts["tags"])) {
233
            $this->addTags($posts["tags"], $postId);
234
        }
235
236
        //checking result and redirecting
237
        if ($postUpdate) {
238
            $this->alertBox->setAlert("Post " . $title . " Updated");
239
            $this->container->getResponse()->redirect("admin/post/modify/" . $postSlug);
240
        }
241
        $this->alertBox->setAlert("Error updating " . $title, "error");
242
        $this->container->getResponse()->redirect("admin/post/modify/" . $originalPostSlug);
243
    }
244
245
246
    /**
247
     * deletes a specific post
248
     * @param int $postId
249
     * @throws \Exception
250
     */
251
    public function deletePost(int $postId)
252
    {
253
        $postTitle = $this->postModel->getTitleFromId($postId);
254
        //first remove tags or foreign key error
255
        $this->tagModel->removeTagsOnPost($postId);
256
        $removedPost = $this->postModel->deletePost($postId);
257
258
        if ($removedPost) {
259
            $this->alertBox->setAlert("Post " . $postTitle . " deleted");
260
        }
261
262
        $this->response->redirect("admin/post/list/");
263
    }
264
}