Completed
Pull Request — master (#18)
by
unknown
04:15
created

CommentController   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 291
Duplicated Lines 13.4 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 10
Bugs 3 Features 4
Metric Value
wmc 17
lcom 1
cbo 3
dl 39
loc 291
rs 10
c 10
b 3
f 4

15 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 0 5 1
A setupAction() 0 5 1
A listAction() 11 11 1
A viewAction() 10 10 1
A addAction() 0 15 1
B createAddCommentForm() 0 41 1
A callbackSubmitAddComment() 0 20 1
A callbackSubmitFailAddComment() 0 6 1
A callbackSuccess() 0 6 1
A callbackFail() 0 6 1
A editAction() 18 18 2
B createEditCommentForm() 0 45 1
A callbackSubmitUpdateComment() 0 17 1
A callbackSubmitFailUpdateComment() 0 5 1
A deleteAction() 0 10 2

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
 * 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
    }
22
23
    /**
24
     * Setup initial table for users.
25
     *
26
     * @return void
27
     */
28
    public function setupAction()
29
    {
30
        $this->comments->init();
31
        $this->redirectTo($_SERVER['HTTP_REFERER']);
32
    }
33
    /**
34
     * List all comments for all flows.
35
     *
36
     * @return void
37
     */
38 View Code Duplication
    public function listAction()
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...
39
    {
40
        $all = $this->comments->findAll();
41
        $flow = $this->request->getRoute();
0 ignored issues
show
Documentation introduced by
The property request 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...
42
        $link = $this->url->create('comment/add/' . $flow);
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...
43
        $this->theme->setTitle("List all users");
0 ignored issues
show
Documentation introduced by
The property theme 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...
44
        $this->views->add('comment/commentsdb', [
0 ignored issues
show
Documentation introduced by
The property views 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...
45
            'comments' => $all,
46
            'comment_link' => $link,
47
        ]);
48
    }
49
    /**
50
     * View all comments in page flow.
51
     *
52
     * @return void
53
     */
54 View Code Duplication
    public function viewAction()
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...
55
    {
56
        $flow = $this->request->getRoute();
0 ignored issues
show
Documentation introduced by
The property request 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
        $all = $this->comments->findFlow($flow);
58
        $link = $this->url->create('comment/add/' . $flow);
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...
59
        $this->views->add('comment/commentsdb', [
0 ignored issues
show
Documentation introduced by
The property views 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...
60
            'comments' => $all,
61
            'comment_link' => $link,
62
        ]);
63
    }
64
65
    /**
66
     * Add new comment.
67
     *
68
     * @param string $route to page for comment flow.
69
     *
70
     * @return void
71
     */
72
    public function addAction($route = null)
0 ignored issues
show
Unused Code introduced by
The parameter $route 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...
73
    {
74
        // Route parts are are in argument array. Glue them together again.
75
        $route = implode("/", func_get_args());
76
        // TODO: Need to sweep session? How?
77
        // Set saveInSession = false instead.
78
        $this->di->session(); // Will load the session service which also starts the session
79
        $form = $this->createAddCommentForm($route);
80
        $form->check([$this, 'callbackSuccess'], [$this, 'callbackFail']);
81
        $this->di->theme->setTitle("Add user");
82
        $this->di->views->add('default/page', [
83
            'title' => "Add Comment",
84
            'content' => $form->getHTML()
85
        ]);
86
    }
87
    private function createAddCommentForm($route)
88
    {
89
        return $this->di->form->create([], [
90
            'content' => [
91
                'type'        => 'textarea',
92
                'label'       => 'Comment:',
93
                'required'    => false,
94
                // 'validation'  => ['not_empty'],
95
            ],
96
            'name' => [
97
                'type'        => 'text',
98
                'label'       => 'Name:',
99
                'required'    => true,
100
                'validation'  => ['not_empty'],
101
            ],
102
            'web' => [
103
                'type'        => 'text',
104
                'label'       => 'Homepage:',
105
                'required'    => false,
106
                // 'validation'  => ['not_empty'],
107
            ],
108
            'mail' => [
109
                'type'        => 'text',
110
                'required'    => true,
111
                'label'       => 'Email:',
112
                'validation'  => ['not_empty', 'email_adress'],
113
            ],
114
            'flow' => [
115
                'type'        => 'hidden',
116
                'value'       => $route,
117
            ],
118
            'submit' => [
119
                'type'      => 'submit',
120
                'callback'  => [$this, 'callbackSubmitAddComment'],
121
            ],
122
            'submit-fail' => [
123
                'type'      => 'submit',
124
                'callback'  => [$this, 'callbackSubmitFailAddComment'],
125
            ],
126
        ]);
127
    }
128
    /**
129
     * Callback for submit-button.
130
     *
131
     */
132
    public function callbackSubmitAddComment($form)
133
    {
134
        // $form->AddOutput("<p>DoSubmit(): Form was submitted.<p>");
135
        // $form->AddOutput("<p>Do stuff (save to database) and return true (success) or false (failed processing)</p>");
136
        // Save comment to database
137
        $now = time();
138
        $this->comments->save([
139
            'flow' => $form->Value('flow'),
140
            'content' => $form->Value('content'),
141
            'name' => $form->Value('name'),
142
            'web' => $form->Value('web'),
143
            'mail' => $form->Value('mail'),
144
            'created' => $now,
145
        ]);
146
147
        // $form->AddOutput("<p><b>Name: " . $form->Value('name') . "</b></p>");
148
        // $form->AddOutput("<p><b>Email: " . $form->Value('mail') . "</b></p>");
149
        $form->saveInSession = false;
150
        return true;
151
    }
152
    /**
153
     * Callback for submit-button.
154
     *
155
     */
156
    public function callbackSubmitFailAddComment($form)
157
    {
158
        // TODO: Remove this?
159
        $form->AddOutput("<p><i>DoSubmitFail(): Form was submitted but I failed to process/save/validate it</i></p>");
160
        return false;
161
    }
162
    /**
163
     * Callback What to do if the form was submitted?
164
     *
165
     */
166
    public function callbackSuccess($form)
167
    {
168
        $form->AddOUtput("<p><i>Form was submitted and the callback method returned true.</i></p>");
169
        // Redirect to page posted from.
170
        $this->redirectTo($form->Value('flow'));
171
    }
172
    /**
173
     * Callback What to do when form could not be processed?
174
     *
175
     */
176
    public function callbackFail($form)
177
    {
178
        $form->AddOutput("<p><i>Form was submitted and the Check() method returned false.</i></p>");
179
        // Redirect to comment form.
180
        $this->redirectTo();
181
    }
182
183
    /**
184
     * Edit comment.
185
     *
186
     * @param string $acronym of user to update.
0 ignored issues
show
Bug introduced by
There is no parameter named $acronym. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
187
     *
188
     * @return void
189
     */
190 View Code Duplication
    public function editAction($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...
191
    {
192
        $this->di->session(); // Will load the session service which also starts the session
193
        $all = $this->comments->query()
194
            ->where("id = '$id'")
195
            ->execute();
196
        if (count($all)!=1) {
197
            die("Comment with id $id not found.");
198
        }
199
        $comment = $this->comments->find($id);
200
        $form = $this->createEditCommentForm($comment);
201
        $form->check([$this, 'callbackSuccess'], [$this, 'callbackFail']);
202
        $this->di->theme->setTitle("Edit comment");
203
        $this->di->views->add('default/page', [
204
            'title' => "Edit comment",
205
            'content' => $form->getHTML()
206
        ]);
207
    }
208
    private function createEditCommentForm($comment = null)
209
    {
210
        return $this->di->form->create([], [
211
            'content' => [
212
                'type'        => 'textarea',
213
                'value'       => $comment->content,
214
                'label'       => 'Comment:',
215
                'required'    => false,
216
                // 'validation'  => ['not_empty'],
217
            ],
218
            'name' => [
219
                'type'        => 'text',
220
                'value'       => $comment->name,
221
                'label'       => 'Name of person:',
222
                'required'    => true,
223
                'validation'  => ['not_empty'],
224
            ],
225
            'web' => [
226
                'type'        => 'text',
227
                'value'       => $comment->web,
228
                'label'       => 'Homepage:',
229
                'required'    => false,
230
                // 'validation'  => ['not_empty'],
231
            ],
232
            'mail' => [
233
                'type'        => 'text',
234
                'value'       => $comment->mail,
235
                'required'    => true,
236
                'label'       => 'Email:',
237
                'validation'  => ['not_empty', 'email_adress'],
238
            ],
239
            'flow' => [
240
                'type'        => 'hidden',
241
                'value'       => $comment->flow,
242
            ],
243
            'submit' => [
244
                'type'      => 'submit',
245
                'callback'  => [$this, 'callbackSubmitUpdateComment'],
246
            ],
247
            'submit-fail' => [
248
                'type'      => 'submit',
249
                'callback'  => [$this, 'callbackSubmitFailUpdateComment'],
250
            ],
251
        ]);
252
    }
253
    public function callbackSubmitUpdateComment($form)
254
    {
255
        // $form->AddOutput("<p>DoSubmit(): Form was submitted.<p>");
256
        // $form->AddOutput("<p>Do stuff (save to database) and return true (success) or false (failed processing)</p>");
257
        // Save user data to database
258
        $this->comments->save([
259
            'content' => $form->Value('content'),
260
            'name' => $form->Value('name'),
261
            'web' => $form->Value('web'),
262
            'mail' => $form->Value('mail'),
263
        ]);
264
265
        // $form->AddOutput("<p><b>Name: " . $form->Value('name') . "</b></p>");
266
        // $form->AddOutput("<p><b>Email: " . $form->Value('mail') . "</b></p>");
267
        $form->saveInSession = false;
268
        return true;
269
    }
270
    /**
271
     * Callback for submit-button.
272
     *
273
     */
274
    public function callbackSubmitFailUpdateComment($form)
275
    {
276
        $form->AddOutput("<p><i>DoSubmitFail(): Form was submitted but I failed to process/save/validate it</i></p>");
277
        return false;
278
    }
279
280
281
282
    /**
283
     * Delete a comment.
284
     *
285
     * @return void
286
     */
287
    public function deleteAction()
288
    {
289
        $id = $this->request->getGet('id');
0 ignored issues
show
Documentation introduced by
The property request 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...
290
        if (!isset($id)) {
291
            die("Missing id");
292
        }
293
294
        $res = $this->comments->delete($id);
0 ignored issues
show
Unused Code introduced by
$res is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
295
        $this->redirectTo($_SERVER['HTTP_REFERER']);
296
    }
297
}
298