Completed
Pull Request — master (#20)
by Fredrik
03:15
created

CommentController::callbackSuccess()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 2
Metric Value
c 4
b 1
f 2
dl 0
loc 6
rs 9.4285
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * class for commenting
4
 */
5
namespace Anax\CommentDb;
6
7
class CommentController implements \Anax\DI\IInjectionAware
8
{
9
    use \Anax\DI\TInjectable,
10
    \Anax\MVC\TRedirectHelpers;
11
12
    /**
13
     * Initialize the controller.
14
     *
15
     * @return void
16
     */
17
    public function initialize()
18
    {
19
        $this->comments = new \Anax\CommentDb\CommentsInDb();
0 ignored issues
show
Bug introduced by
The property comments does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
20
        $this->comments->setDI($this->di);
0 ignored issues
show
Bug introduced by
It seems like $this->di can also be of type array or null; however, Anax\DI\TInjectable::setDI() does only seem to accept object<Anax\DI\class>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
21
        $this->users = new \Anax\Users\User();
0 ignored issues
show
Bug introduced by
The property users does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
22
        $this->users->setDI($this->di);
0 ignored issues
show
Bug introduced by
It seems like $this->di can also be of type array or null; however, Anax\DI\TInjectable::setDI() does only seem to accept object<Anax\DI\class>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
23
    }
24
25
    /**
26
     * Setup initial table for users.
27
     *
28
     * @return void
29
     */
30
    public function setupAction()
31
    {
32
        $this->comments->init();
33
        // $this->redirectTo($_SERVER['HTTP_REFERER']);
34
    }
35
36
    /**
37
     * Add new comment.
38
     *
39
     * @param integer $id of question or answer
40
     * @param string $q_or_a 'q' or 'a' for question or answer comment
41
     *
42
     * @return void
43
     */
44 View Code Duplication
    public function addAction($id, $q_or_a)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
45
    {
46
        if ($this->users->loggedIn()) {
47
            $this->di->session(); // Will load the session service which also starts the session
48
            $form = $this->createAddCommentForm($id, $q_or_a);
49
            $form->check([$this, 'callbackSuccess'], [$this, 'callbackFail']);
50
            // $this->di->theme->setTitle("Kommentera");
51
            $this->di->views->add('default/page', [
52
                'title' => "Kommentera",
53
                'content' => $form->getHTML()
54
            ]);
55
        } else {
56
            $this->redirectTo($this->url->create('users/login'));
0 ignored issues
show
Documentation introduced by
The property url does not exist on object<Anax\CommentDb\CommentController>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
57
        }
58
    }
59
    private function createAddCommentForm($id, $q_or_a)
60
    {
61
        return $this->di->form->create([], [
62
            'content' => [
63
                'type'        => 'textarea',
64
                'label'       => 'Comment:',
65
                'required'    => true,
66
                'validation'  => ['not_empty'],
67
            ],
68
            'q_or_a_id' => [
69
                'type'        => 'hidden',
70
                'value'       => $id,
71
            ],
72
            'q_or_a' => [
73
                'type'        => 'hidden',
74
                'value'       => $q_or_a,
75
            ],
76
            'submit' => [
77
                'type'      => 'submit',
78
                'callback'  => [$this, 'callbackSubmitAddComment'],
79
            ],
80
            // 'submit-fail' => [
81
            //     'type'      => 'submit',
82
            //     'callback'  => [$this, 'callbackSubmitFailAddComment'],
83
            // ],
84
        ]);
85
    }
86
    /**
87
     * Callback for submit-button.
88
     *
89
     */
90 View Code Duplication
    public function callbackSubmitAddComment($form)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
    {
92
        // $form->AddOutput("<p>DoSubmit(): Form was submitted.<p>");
93
        // $form->AddOutput("<p>Do stuff (save to database) and return true (success) or false (failed processing)</p>");
94
        // Save comment to database
95
        $now = time();
96
        $this->comments->save([
97
            'content' => $form->Value('content'),
98
            'q_or_a' => $form->Value('q_or_a'),
99
            'q_or_a_id' => $form->Value('q_or_a_id'),
100
            'user_id' => $this->users->loggedInUser()->id,
101
            'created' => $now,
102
        ]);
103
104
        // $form->AddOutput("<p><b>Id: " . $form->Value('q_or_a_id') . "</b></p>");
105
        // $form->AddOutput("<p><b>Q or A: " . $form->Value('q_or_a') . "</b></p>");
106
        // $form->AddOutput("<p><b>Kommentar: " . $form->Value('content') . "</b></p>");
107
        $form->saveInSession = false;
108
        // Unset ShowFormCorA so comment form wont be shown when returning to question.
109
        $this->session->set('ShowFormCorA', '');
0 ignored issues
show
Documentation introduced by
The property session does not exist on object<Anax\CommentDb\CommentController>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
110
111
        return true;
112
    }
113
    /**
114
     * Callback for submit-button.
115
     *
116
     */
117
    public function callbackSubmitFailAddComment($form)
0 ignored issues
show
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
118
    {
119
        // TODO: Remove this?
120
        // $form->AddOutput("<p><i>DoSubmitFail(): Form was submitted but I failed to process/save/validate it</i></p>");
121
        return false;
122
    }
123
    /**
124
     * Callback What to do if the form was submitted?
125
     *
126
     */
127
    public function callbackSuccess($form)
0 ignored issues
show
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
128
    {
129
        // $form->AddOUtput("<p><i>Form was submitted and the callback method returned true.</i></p>");
130
        // Redirect to page posted from.
131
        $this->redirectTo();
132
    }
133
    /**
134
     * Callback What to do when form could not be processed?
135
     *
136
     */
137
    public function callbackFail($form)
0 ignored issues
show
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
138
    {
139
        // $form->AddOutput("<p><i>Form was submitted and the Check() method returned false.</i></p>");
140
        // Redirect to comment form.
141
        $this->redirectTo();
142
    }
143
144
145
    /**
146
     * Delete a comment.
147
     *
148
     * @return void
149
     */
150
//     public function deleteAction()
151
//     {
152
//         $id = $this->request->getGet('id');
153
//         if (!isset($id)) {
154
//             die("Missing id");
155
//         }
156
//
157
//         $res = $this->comments->delete($id);
158
//         $this->redirectTo($_SERVER['HTTP_REFERER']);
159
//     }
160
}
161