Passed
Push — main ( fe10cd...94aef8 )
by Pan
02:57
created

PostController::showAction()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 41
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 29
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 41
rs 8.8337
1
<?php
2
3
namespace Pan\Post;
4
5
use Anax\Commons\ContainerInjectableInterface;
6
use Anax\Commons\ContainerInjectableTrait;
7
8
// use Anax\Route\Exception\ForbiddenException;
9
// use Anax\Route\Exception\NotFoundException;
10
// use Anax\Route\Exception\InternalErrorException;
11
12
/**
13
 * A sample controller to show how a controller class can be implemented.
14
 */
15
class PostController implements ContainerInjectableInterface
16
{
17
    use ContainerInjectableTrait;
18
19
20
21
    /**
22
     * @var $data description
0 ignored issues
show
Documentation Bug introduced by
The doc comment $data at position 0 could not be parsed: Unknown type name '$data' at position 0 in $data.
Loading history...
23
     */
24
    private $currentUser;
25
    private $db;
26
    private $userId;
27
28
29
30
    // /**
31
    //  * The initialize method is optional and will always be called before the
32
    //  * target method/action. This is a convienient method where you could
33
    //  * setup internal properties that are commonly used by several methods.
34
    //  *
35
    //  * @return void
36
    //  */
37
    public function initialize() : void
38
    {
39
        // Get the current user from session
40
        $session = $this->di->get("session");
41
        // var_dump($session);
42
        $this->currentUser = $session->get("username");
43
44
        // Connect the database
45
        $this->db = $this->di->get("db");
46
        $this->db->connect();
47
        if ($this->currentUser !=null) {
48
            $sql = "SELECT id from users where username = ?;";
49
            $res = $this->db->executeFetchAll($sql, [$this->currentUser]);
50
            $this->userId = $res[0]->id;
51
        }
52
    }
53
54
55
56
    /**
57
     * Show all items.
58
     *
59
     * @return object as a response object
60
     */
61
    public function indexActionGet() : object
62
    {
63
        $page = $this->di->get("page");
64
65
        // Get settings from GET or use defaults
66
        $request = $this->di->get("request");
67
        $orderBy = $request->getGet("orderby") ?: "created";
68
        $order = $request->getGet("order") ?: "asc";
69
70
        $sql = "SELECT * FROM v_all ORDER BY $orderBy $order;";
71
72
        $posts = $this->db->executeFetchAll($sql);
73
74
        $page->add("post/view-all", [
75
            "items" => $posts,
76
        ]);
77
78
        return $page->render([
79
            "title" => "All Posts",
80
        ]);
81
    }
82
83
84
85
    /**
86
     * Handler with form to create a new item.
87
     *
88
     * @return object as a response object
89
     */
90
    public function createActionGet() : object
91
    {
92
        if ($this->currentUser) {
93
            $page = $this->di->get("page");
94
            $page->add("post/create");
95
96
            return $page->render([
97
                "title" => "Ask Question",
98
            ]);
99
        }
100
        $response = $this->di->get("response");
101
        return $response->redirect("user/login");
102
    }
103
104
105
    public function createActionPost() : object
106
    {
107
        $request = $this->di->get("request");
108
        $response = $this->di->get("response");
109
        $submit = $request->getPost("submit") ?: null;
110
111
        if ($submit) {
112
            $title = $request->getPost("Title") ?: null;
113
            $content = $request->getPost("Body") ?: null;
114
            $tags = $request->getPost("Tags") ?: null;
115
116
            $sql = "INSERT INTO posts (title, content, user_id) VALUES (?, ?, ?);";
117
            $this->db->execute($sql, [$title, $content, $this->userId]);
118
            $lastInsertId = $this->db->lastInsertId();
119
            var_dump($lastInsertId);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($lastInsertId) looks like debug code. Are you sure you do not want to remove it?
Loading history...
120
            $tagsArray = explode(",", $tags);
0 ignored issues
show
Bug introduced by
It seems like $tags can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

120
            $tagsArray = explode(",", /** @scrutinizer ignore-type */ $tags);
Loading history...
121
            foreach ($tagsArray as $value) {
122
                $sql = "INSERT INTO post2tag (post_id, tag_name) VALUES (?, ?);";
123
                $this->db->execute($sql, [$lastInsertId, trim($value)]);
124
            }
125
126
            return $response->redirect("post");
127
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 111 is false. This is incompatible with the type-hinted return object. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
128
    }
129
130
    /**
131
     * Handler with form to update an item.
132
     *
133
     * @param int $id the id to answer.
134
     *
135
     * @return object as a response object
136
     */
137
    public function answerActionPost() : object
138
    {
139
        $page = $this->di->get("page");
0 ignored issues
show
Unused Code introduced by
The assignment to $page is dead and can be removed.
Loading history...
140
        $request = $this->di->get("request");
141
        $submit = $request->getPost("submit") ?: null;
142
        // one has to login to answer the question
143
        if ($this->currentUser) {
144
            if ($submit) {
145
                $post_id = $request->getPost("post_id") ?: null;
146
                $comment = $request->getPost("answer") ?: null;
147
148
                $sql = "INSERT INTO comments (comment, user_id, post_id, answer) VALUES (?, ?, ?, ?);";
149
                $this->db->execute($sql, [$comment, $this->userId, $post_id, 1]);
150
                $response = $this->di->get("response");
151
                return $response->redirect("post/show/$post_id");
152
            }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 144 is false. This is incompatible with the type-hinted return object. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
153
        } else {
154
            $response = $this->di->get("response");
155
            return $response->redirect("user/login");
156
        }
157
    }
158
159
    /**
160
     * Handler to view an item.
161
     *
162
     * @param int $id the id to view.
163
     *
164
     * @return object as a response object
165
     */
166
    public function showAction(int $id) : object
167
    {
168
        $page = $this->di->get("page");
169
        $postid = $id;
170
        $request = $this->di->get("request");
171
        $orderBy = $request->getGet("orderby") ?: "created";
172
        $order = $request->getGet("order") ?: "asc";
173
        $sql = "SELECT * from posts WHERE id=?;";
174
        $posts = $this->db->executeFetchAll($sql, [$postid]);
175
        $sql = "select * from post2tag where post_id=?;";
176
        $posttags = $db->executeFetchAll($sql, [$item->id]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $db seems to be never defined.
Loading history...
Unused Code introduced by
The assignment to $posttags is dead and can be removed.
Loading history...
Comprehensibility Best Practice introduced by
The variable $item seems to be never defined.
Loading history...
177
        $sql = "SELECT sum(score) as postscore from post_votes where post_id=?;";
178
        $score = $this->db->executeFetchAll($sql, [$item->id]);
0 ignored issues
show
Unused Code introduced by
The assignment to $score is dead and can be removed.
Loading history...
179
        $sql = "SELECT sum(answer) as totalanswer from comments where post_id=?;";
180
        $answer = $this->db->executeFetchAll($sql, [$item->id]);
181
182
        $sql = "SELECT * from v_comments_user WHERE post_id=? and answer=1 order by accepted desc, $orderBy $order;";
183
        //Get the answers for the post
184
        $answers = $this->db->executeFetchAll($sql, [$postid]);
185
        $sql = "SELECT * from v_comments_user WHERE post_id=? and answer=0 and ISNULL(comment_reply_id);";
186
        // Get the comments for the post
187
        $comments0 = $this->db->executeFetchAll($sql, [$postid]);
188
189
190
        // check if the current user is the owner of the question, if yes, show the accepted answer button otherwise not
191
        // var_dump($this->currentUser,$posts[0]->username  );
192
        $isOwner=true;
193
        if ($this->currentUser != $posts[0]->username ) {
194
            $isOwner = false;
195
        }
196
        $page->add("post/show",
197
            ["post"  => $posts[0],
198
             "postscore"  => $postscore[0]->postscore?:0,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $postscore does not exist. Did you maybe mean $posts?
Loading history...
199
             "totalanswer"  => $answer[0]->totalanswer?:0,
200
            "answers"  => $answers,
201
            "comments0"  => $comments0,
202
            "isOwner"  => $isOwner,
203
            ]);
204
205
        return $page->render([
206
            "title" => "Show a Post",
207
        ]);
208
    }
209
210
    public function uppvoteAction(int $id) : object
211
    {
212
        $page = $this->di->get("page");
0 ignored issues
show
Unused Code introduced by
The assignment to $page is dead and can be removed.
Loading history...
213
214
        $sql = "INSERT INTO post_votes (score, post_id, user_id) VALUES (?, ?, ?);";
215
        $this->db->execute($sql, [1, $id, $this->userId]);
216
217
218
        $response = $this->di->get("response");
219
        return $response->redirect("post/show/$id");
220
    }
221
222
    public function downvoteAction(int $id) : object
223
    {
224
        $page = $this->di->get("page");
0 ignored issues
show
Unused Code introduced by
The assignment to $page is dead and can be removed.
Loading history...
225
226
        $sql = "INSERT INTO post_votes (score, post_id, user_id) VALUES (?, ?, ?);";
227
        $this->db->execute($sql, [-1, $id, $this->userId]);
228
229
230
        $response = $this->di->get("response");
231
        return $response->redirect("post/show/$id");
232
    }
233
}
234