Passed
Push — Showing-Posts ( b1a8d3...c3e4ac )
by Stone
02:25
created

PostModel::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Models;
4
5
use Core\Constant;
6
use Core\Container;
7
use Core\Model;
8
use Core\Traits\StringFunctions;
9
10
class PostModel extends Model
11
{
12
    use StringFunctions;
13
14
    private $postsTbl;
15
    private $categoriesTbl;
16
    private $usersTbl;
17
18
    public function __construct(Container $container)
19
    {
20
        parent::__construct($container);
21
        $this->postsTbl = $this->getTablePrefix('posts');
22
        $this->categoriesTbl = $this->getTablePrefix('categories');
23
        $this->usersTbl = $this->getTablePrefix('users');
24
    }
25
26
    /**
27
     * the base Select SQL to get the information from the post table and joined tables
28
     * @return string
29
     */
30
    private function basePostSelect():string
31
    {
32
        $sql = "SELECT idposts, title, post_image,article,$this->postsTbl.last_update, posts_slug, categories_idcategories, category_name, published, on_front_page, categories_slug, pseudo as author, idusers
33
                FROM $this->postsTbl INNER JOIN $this->categoriesTbl ON $this->postsTbl.categories_idcategories = $this->categoriesTbl.idcategories
34
                INNER JOIN $this->usersTbl ON $this->postsTbl.author_iduser = $this->usersTbl.idusers";
35
        return $sql;
36
    }
37
38
    /**
39
     * add the excerpt to a post list
40
     * @param array $posts
41
     * @return array
42
     * @throws \ErrorException
43
     */
44
    private function addExcerpt(array $posts):array
45
    {
46
        $sendResults = [];
47
        //we create the excerpt for the text and add it to the object
48
        foreach ($posts as $post) {
49
            $post->{'excerpt'} = $this->getExcerpt($post->article);
50
            $sendResults[] = $post;
51
        }
52
        return $sendResults;
53
    }
54
55
    /**
56
     * get all the posts with details. Only selecting posts that are published
57
     * @param int $offset where to start (for pagination)
58
     * @param int $limit the number of posts
59
     * @param bool $isFrontPage extract only front page posts
60
     * @return array list of posts
61
     * @throws \ErrorException
62
     */
63
    private function getAllPublishedPosts(int $offset, int $limit, bool $isFrontPage = false): array
64
    {
65
        $sql = $this->basePostSelect();
66
        $sql .= " WHERE published = 1";
67
        if ($isFrontPage) {
68
            $sql .= " AND on_front_page = 1";
69
        }
70
        $sql .= " ORDER BY $this->postsTbl.creation_date DESC";
71
        $sql .= " LIMIT :limit OFFSET :offset";
72
        $this->query($sql);
73
        $this->bind(":limit", $limit);
74
        $this->bind(":offset", $offset);
75
        $this->execute();
76
        $results = $this->fetchAll();
77
        return $this->addExcerpt($results);
78
    }
79
80
    /**
81
     * get the total number of posts, useful for pagination
82
     * @return int
83
     * @throws \Exception
84
     */
85
    public function totalNumberPosts():int
86
    {
87
        $sql = "SELECT COUNT(*) FROM $this->postsTbl WHERE published = 1";
88
        $this->query($sql);
89
        $this->execute();
90
        return $this->stmt->fetchColumn();
91
    }
92
93
    /**
94
     * get the total number of posts in a category, useful for pagination
95
     * @param int $categoryId
96
     * @return int
97
     * @throws \Exception
98
     */
99
    public function totalNumberPostsInCategory(int $categoryId):int
100
    {
101
        $sql = "SELECT COUNT(*) FROM $this->postsTbl WHERE published = 1 AND categories_idcategories = :categoryId ";
102
        $this->query($sql);
103
        $this->bind(":categoryId", $categoryId, \PDO::PARAM_INT);
104
        $this->execute();
105
        return $this->stmt->fetchColumn();
106
    }
107
108
    /**
109
     * get the list of front posts
110
     * @param int $offset
111
     * @param int $limit
112
     * @return array
113
     * @throws \ErrorException
114
     */
115
    public function getFrontPosts(int $offset = 0, int $limit = Constant::FRONT_PAGE_POSTS):array
116
    {
117
        return $this->getAllPublishedPosts($offset, $limit, true);
118
    }
119
120
    /**
121
     * get the list of all the posts.
122
     * @param int $offset
123
     * @param int $limit
124
     * @return array
125
     * @throws \ErrorException
126
     */
127
    public function getPosts(int $offset = 0, int $limit = Constant::POSTS_PER_PAGE):array
128
    {
129
        return $this->getAllPublishedPosts($offset, $limit, false);
130
    }
131
132
    /**
133
     * get all the posts from a certain category
134
     * @param int $categoryId the id of the category
135
     * @param int $offset the offset for pagination
136
     * @param int $limit the limit to display
137
     * @return array list of posts in set category
138
     * @throws \Exception
139
     */
140
    public function getPostsInCategory(int $categoryId, int $offset = 0, int $limit = Constant::POSTS_PER_PAGE): array
141
    {
142
        $sql = $this->basePostSelect();
143
        $sql .= " WHERE categories_idcategories = :categoryId 
144
                ORDER BY $this->postsTbl.creation_date DESC
145
                LIMIT :limit OFFSET :offset;";
146
        $this->query($sql);
147
        $this->bind(":categoryId", $categoryId, \PDO::PARAM_INT);
148
        $this->bind(":limit", $limit);
149
        $this->bind(":offset", $offset);
150
        $this->execute();
151
152
        $results = $this->fetchAll();
153
        $sendResults = [];
154
        //we create the excerpt for the text and add it to the object
155
        foreach ($results as $result) {
156
            $result->{'excerpt'} = $this->getExcerpt($result->article);
157
            $sendResults[] = $result;
158
        }
159
        return $sendResults;
160
    }
161
162
163
164
165
    /**
166
     * get a single post from it's ID
167
     * @param int $postid the post ID to get
168
     * @return array the single post details
169
     * @throws \Exception
170
     */
171
    public function getSinglePost(int $postid):array
172
    {
173
        $sql = $this->basePostSelect();
174
        $sql .= " WHERE idposts = :postId;";
175
        $this->query($sql);
176
        $this->bind(":postId", $postid, \PDO::PARAM_INT);
177
        $this->execute();
178
179
        return $this->fetch();
180
    }
181
182
    /**
183
     * Create a new post
184
     * @param string $title
185
     * @param string $postImage
186
     * @param int $idCategory
187
     * @param string $article
188
     * @param int $idUser
189
     * @param int $published
190
     * @param int $onFrontPage
191
     * @param string $postSlug
192
     * @return int the id of created post
193
     * @throws \Exception
194
     */
195
    public function newPost(
196
        string $title,
197
        string $postImage,
198
        int $idCategory,
199
        string $article,
200
        int $idUser,
201
        int $published,
202
        int $onFrontPage,
203
        string $postSlug
204
    ):int
205
    {
206
        $sql = "
207
          INSERT INTO $this->postsTbl (title, post_image, categories_idcategories, article, author_iduser, creation_date, last_update, published, on_front_page, posts_slug)
208
          VALUES (:title, :post_image, :categories_idcategories, :article, :author_iduser, NOW(), NOW(), :published, :on_front_page, :posts_slug)
209
        ";
210
        $this->query($sql);
211
        $this->bind(':title', $title);
212
        $this->bind(':post_image', $postImage);
213
        $this->bind(':categories_idcategories', $idCategory);
214
        $this->bind(':article', $article);
215
        $this->bind(':author_iduser', $idUser);
216
        $this->bind(':published', $published);
217
        $this->bind(':on_front_page', $onFrontPage);
218
        $this->bind(':posts_slug', $postSlug);
219
220
        $this->execute();
221
222
        return $this->dbh->lastInsertId();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->dbh->lastInsertId() returns the type string which is incompatible with the type-hinted return integer.
Loading history...
223
    }
224
225
    /**
226
     * Update a post with new values
227
     * @param int $postId
228
     * @param string $title
229
     * @param string $postImage
230
     * @param int $idCategory
231
     * @param string $article
232
     * @param int $published
233
     * @param int $onFrontPage
234
     * @param string $postSlug
235
     * @return bool success
236
     * @throws \Exception
237
     */
238
    public function modifyPost(
239
        int $postId,
240
        string $title,
241
        string $postImage,
242
        int $idCategory,
243
        string $article,
244
        int $published,
245
        int $onFrontPage,
246
        string $postSlug
247
    ):bool
248
    {
249
        $sql = "
250
            UPDATE $this->postsTbl 
251
            SET 
252
                title = :title,
253
                post_image = :postImage,
254
                categories_idcategories = :idCategory,
255
                article = :article,
256
                last_update = NOW(),
257
                published = :published,
258
                on_front_page = :onFrontPage,
259
                posts_slug = :postSlug
260
            WHERE
261
              idposts = :postId
262
        ;";
263
        $this->query($sql);
264
        $this->bind(":title", $title);
265
        $this->bind(":postImage", $postImage);
266
        $this->bind(":idCategory", $idCategory);
267
        $this->bind(":article", $article);
268
        $this->bind(":published", $published);
269
        $this->bind(":onFrontPage", $onFrontPage);
270
        $this->bind(":postSlug", $postSlug);
271
        $this->bind(":postId", $postId);
272
273
        return $this->execute();
274
    }
275
276
277
}