Test Failed
Push — master ( 48da91...4d2acf )
by Nicklas
01:59
created

CreateCommentForm::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 1
1
<?php
2
3
namespace Nicklas\Comment\HTMLForm\Comment;
4
5
use \Anax\HTMLForm\FormModel;
6
use \Anax\DI\DIInterface;
7
use \Nicklas\Comment\User;
8
use \Nicklas\Comment\Comment;
9
10
/**
11
 * Example of FormModel implementation.
12
 */
13
class CreateCommentForm extends FormModel
14
{
15
    /**
16
     * Constructor injects with DI container.
17
     *
18
     * @param Anax\DI\DIInterface $di a service container
19
     */
20
    public function __construct(DIInterface $di)
21
    {
22
        parent::__construct($di);
23
        $this->form->create(
24
            [
25
                "id" => __CLASS__,
26
            ],
27
            [
28
                "comment" => [
29
                    "type"        => "textarea",
30
                    "label" => false,
31
                    "placeholder" => "Comment here"
32
                ],
33
34
                "submit" => [
35
                    "type" => "submit",
36
                    "value" => "Skicka",
37
                    "callback" => [$this, "callbackSubmit"]
38
                ],
39
            ]
40
        );
41
    }
42
43
44
45
    /**
46
     * Callback for submit-button which should return true if it could
47
     * carry out its work and false if something failed.
48
     *
49
     * @return boolean true if okey, false if something went wrong.
50
     */
51
    public function callbackSubmit()
52
    {
53
        // Get values from the submitted form
54
        $sentComment       = $this->form->value("comment");
55
56
        $comment = new Comment();
57
        $comment->setDb($this->di->get("db"));
58
59
        if (!$this->di->get('session')->has("user")) {
60
            $this->form->addOutput("You need to log in");
61
            return false;
62
        }
63
64
        $user = $this->di->get('session')->get("user"); # get user name
65
66
        $comment->user = $user;
67
        $comment->comment = $sentComment;
68
        $comment->save();
69
        return true;
70
    }
71
}
72