Completed
Push — master ( 0d0ae6...7c7732 )
by Stone
19s
created

Post::createNewPost()   B

Complexity

Conditions 10
Paths 130

Size

Total Lines 61
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 38
nc 130
nop 0
dl 0
loc 61
rs 7.4166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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