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

AnswersController   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 162
Duplicated Lines 22.22 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 5
Bugs 1 Features 1
Metric Value
wmc 12
c 5
b 1
f 1
lcom 1
cbo 5
dl 36
loc 162
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 0 9 1
A setupAction() 0 6 1
A acceptAction() 0 19 3
A addAction() 15 15 2
A createAddCommentForm() 0 23 1
A callbackSubmitAddAnswer() 21 21 1
A callbackSubmitFailAddComment() 0 6 1
A callbackSuccess() 0 8 1
A callbackFail() 0 6 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Anax\Answers;
4
5
/**
6
 * A controller for "Answers".
7
 *
8
 */
9
class AnswersController implements \Anax\DI\IInjectionAware
10
{
11
    use \Anax\DI\TInjectable,
12
    \Anax\MVC\TRedirectHelpers;
13
14
    /**
15
     * Initialize the controller.
16
     *
17
     * @return void
18
     */
19
    public function initialize()
20
    {
21
        $this->answers = new \Anax\Answers\CAnswers();
0 ignored issues
show
Bug introduced by
The property answers 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->answers->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
        $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...
24
        $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...
25
        $this->questions = new \Anax\Questions\CQuestions();
0 ignored issues
show
Bug introduced by
The property questions 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...
26
        $this->questions->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...
27
    }
28
29
    /**
30
     * Setup initial table for users.
31
     *
32
     * @return void
33
     */
34
    public function setupAction()
35
    {
36
        // echo "<br>" . __FILE__ . " : " . __LINE__ . "<br>";var_dump("Setup Answers!");
37
        $this->answers->init();
38
        // $this->redirectTo('answers/');
39
    }
40
41
    /**
42
     * Accept answer to question
43
     *
44
     * @param integer $id to answer.
45
     *
46
     * @return void
47
     */
48
    public function acceptAction($id)
49
    {
50
        $answer = $this->answers->find($id);
51
        $user = $this->users->loggedInUser();
52
        $question = $this->questions->find($answer->q_id);
53
        if ($user->id == $question->user_id &&
54
            !$question->accepted_answer) {
55
            // Update answer entry in db.
56
            $this->answers->update([
57
                'id'        => $answer->id,
58
                'accepted'  => true,
59
            ]);
60
            $this->questions->update([
61
                'id'        => $question->id,
62
                'accepted_answer'  => true,
63
            ]);
64
        }
65
        $this->redirectTo($_SERVER['HTTP_REFERER']);
66
    }
67
68
    /**
69
     * Add new question
70
     *
71
     * @param integer $question_id for question being answered.
72
     *
73
     * @return void
74
     */
75 View Code Duplication
    public function addAction($question_id = null)
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...
76
    {
77
        if ($this->users->loggedIn()) {
78
            $this->di->session(); // Will load the session service which also starts the session
79
            $form = $this->createAddCommentForm($question_id);
80
            $form->check([$this, 'callbackSuccess'], [$this, 'callbackFail']);
81
            // $this->di->theme->setTitle("Add user");
82
            $this->di->views->add('default/page', [
83
                'title' => "Svara på fråga $question_id",
84
                'content' => $form->getHTML()
85
            ]);
86
        } else {
87
            $this->redirectTo($this->url->create('users/login'));
0 ignored issues
show
Documentation introduced by
The property url does not exist on object<Anax\Answers\AnswersController>. 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...
88
        }
89
    }
90
    private function createAddCommentForm($question_id)
91
    {
92
        return $this->di->form->create([], [
93
            'content' => [
94
                'type'        => 'textarea',
95
                'label'       => 'Svar:',
96
                'required'    => true,
97
                'validation'  => ['not_empty'],
98
            ],
99
            'question_id' => [
100
                'type'        => 'hidden',
101
                'value'       => $question_id,
102
            ],
103
            'submit' => [
104
                'type'      => 'submit',
105
                'callback'  => [$this, 'callbackSubmitAddAnswer'],
106
            ],
107
            // 'submit-fail' => [
108
            //     'type'      => 'submit',
109
            //     'callback'  => [$this, 'callbackSubmitFailAddComment'],
110
            // ],
111
        ]);
112
    }
113
    /**
114
     * Callback for submit-button.
115
     *
116
     */
117 View Code Duplication
    public function callbackSubmitAddAnswer($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...
118
    {
119
        // $form->AddOutput("<p>DoSubmit(): Form was submitted.<p>");
120
        // $form->AddOutput("<p>Do stuff (save to database) and return true (success) or false (failed processing)</p>");
121
122
        // Save comment to database
123
        $now = time();
124
        $this->answers->save([
125
            'content'   => $form->Value('content'),
126
            'user_id'   => $this->users->loggedInUser()->id,
127
            'q_id'      => $form->Value('question_id'),
128
            'vote'      => 0,
129
            'created'   => $now,
130
            'accepted'  => false,
131
        ]);
132
        // $form->AddOutput("<p><b>Name: " . $form->Value('name') . "</b></p>");
133
        // $form->AddOutput("<p><b>Email: " . $form->Value('mail') . "</b></p>");
134
        $form->saveInSession = false;
135
        $this->session->set('ShowFormCorA', '');
0 ignored issues
show
Documentation introduced by
The property session does not exist on object<Anax\Answers\AnswersController>. 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...
136
        return true;
137
    }
138
    /**
139
     * Callback for submit-button.
140
     *
141
     */
142
    public function callbackSubmitFailAddComment($form)
143
    {
144
        // TODO: Remove this?
145
        $form->AddOutput("<p><i>DoSubmitFail(): Form was submitted but I failed to process/save/validate it</i></p>");
146
        return false;
147
    }
148
    /**
149
     * Callback What to do if the form was submitted?
150
     *
151
     */
152
    public function callbackSuccess($form)
153
    {
154
        $form->AddOUtput("<p><i>Form was submitted and the callback method returned true.</i></p>");
155
        // Redirect to page displaying the new question.
156
        // $this->redirectTo($this->url->create('questions/single/' . $this->questions->id));
157
        // $this->redirectTo($this->url->create('questions/single/' . $this->questions->id));
158
        $this->redirectTo();
159
    }
160
    /**
161
     * Callback What to do when form could not be processed?
162
     *
163
     */
164
    public function callbackFail($form)
165
    {
166
        $form->AddOutput("<p><i>Form was submitted and the Check() method returned false.</i></p>");
167
        // Redirect to comment form.
168
        $this->redirectTo();
169
    }
170
}
171