Test Setup Failed
Push — master ( 61c2c6...af32d6 )
by Mihail
06:18
created

Comments   B

Complexity

Total Complexity 21

Size/Duplication

Total Lines 183
Duplicated Lines 3.28 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 8
Bugs 4 Features 0
Metric Value
wmc 21
c 8
b 4
f 0
lcom 1
cbo 17
dl 6
loc 183
rs 7.8571

4 Methods

Rating   Name   Duplication   Size   Complexity  
B actionAdd() 0 35 4
B actionList() 3 59 6
B actionShowanswers() 3 34 6
B actionCount() 0 26 5

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 Apps\Controller\Api;
4
5
use Apps\ActiveRecord\CommentPost;
6
use Apps\ActiveRecord\CommentAnswer;
7
use Apps\ActiveRecord\App as AppRecord;
8
use Apps\Model\Api\Comments\CommentAnswerAdd;
9
use Apps\Model\Api\Comments\CommentPostAdd;
10
use Apps\Model\Api\Comments\EntityCommentData;
11
use Extend\Core\Arch\ApiController;
12
use Ffcms\Core\App;
13
use Ffcms\Core\Helper\Type\Obj;
14
use Ffcms\Core\Helper\Type\Str;
15
use Ffcms\Core\Exception\NotFoundException;
16
use Ffcms\Core\Exception\NativeException;
17
use Ffcms\Core\Exception\ForbiddenException;
18
19
/**
20
 * Class Comments. View and add comments and answers via json based ajax query's
21
 * @package Apps\Controller\Api
22
 */
23
class Comments extends ApiController
24
{
25
    /**
26
     * Add comment or answer via ajax.
27
     * @return string
28
     * @throws NativeException
29
     */
30
    public function actionAdd()
31
    {
32
        $this->setJsonHeader();
33
        $configs = AppRecord::getConfigs('widget', 'Comments');
34
35
        $replayTo = (int)App::$Request->request->get('replay-to');
36
        $model = null;
0 ignored issues
show
Unused Code introduced by
$model 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...
37
        // check if its a answer (comment answer type)
38
        if ($replayTo > 0) {
39
            $model = new CommentAnswerAdd($configs);
0 ignored issues
show
Bug introduced by
It seems like $configs defined by \Apps\ActiveRecord\App::...s('widget', 'Comments') on line 33 can also be of type null or string; however, Apps\Model\Api\Comments\...nswerAdd::__construct() does only seem to accept array, 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...
40
            $model->replayTo = $replayTo;
41
        } else { // sounds like new comment row
42
            $model = new CommentPostAdd($configs);
0 ignored issues
show
Bug introduced by
It seems like $configs defined by \Apps\ActiveRecord\App::...s('widget', 'Comments') on line 33 can also be of type null or string; however, Apps\Model\Api\Comments\...tPostAdd::__construct() does only seem to accept array, 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...
43
            $model->pathway = App::$Security->strip_tags(App::$Request->request->get('pathway'));
44
        }
45
46
        // pass general comment params to model
47
        $model->message = App::$Security->secureHtml((string)App::$Request->request->get('message'));
48
        $model->guestName = App::$Security->strip_tags(App::$Request->request->get('guest-name'));
49
50
        // check model conditions before add new row
51
        if ($model === null || !$model->check()) {
52
            throw new NativeException('Unknown error');
53
        }
54
55
        // add comment post or answer to database and get response active record row
56
        $record = $model->buildRecord();
57
        // pass row to entity builder model
58
        $response = new EntityCommentData($record);
59
60
        return json_encode([
61
            'status' => 1,
62
            'data' => $response->make() // build row to standard format
63
        ]);
64
    }
65
66
    /**
67
     * List comments as json object with defined offset index
68
     * @param int $index
69
     * @return string
70
     * @throws NotFoundException
71
     */
72
    public function actionList($index)
73
    {
74
        // set header
75
        $this->setJsonHeader();
76
        // get configs
77
        $configs = AppRecord::getConfigs('widget', 'Comments');
78
        // items per page
79
        $perPage = (int)$configs['perPage'];
80
        // offset can be only integer
81
        $index = (int)$index;
82
        $offset = $perPage * $index;
83
        // get comment target path and check
84
        $path = (string)App::$Request->query->get('path');
85
        if (Str::likeEmpty($path)) {
86
            throw new NotFoundException('Wrong path');
87
        }
88
89
        // select comments from db and check it
90
        $query = CommentPost::where('pathway', '=', $path);
91
92
        // check if comments is depend of language locale
93 View Code Duplication
        if ((int)$configs['onlyLocale'] === 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
94
            $query = $query->where('lang', '=', App::$Request->getLanguage());
95
        }
96
97
        // get comments with offset and limit
98
        $records = $query->skip($offset)
99
            ->take($perPage)
100
            ->get();
101
102
        // check if records is not empty
103
        if ($records->count() < 1) {
104
            throw new NotFoundException(__('There is no comments found yet. You can be the first!'));
105
        }
106
107
        // build output json data as array
108
        $data = [];
109
        foreach ($records as $comment) {
110
            // prepare specified data to output response, based on entity model
111
            $commentResponse = new EntityCommentData($comment);
112
113
            // build output json data
114
            $data[] = $commentResponse->make();
115
            $commentResponse = null;
0 ignored issues
show
Unused Code introduced by
$commentResponse 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...
116
        }
117
118
        // calculate comments left count
119
        $count = CommentPost::where('pathway', '=', $path)->count();
120
        $count -= $offset + $perPage;
121
        if ($count < 0) {
122
            $count = 0;
123
        }
124
125
        return json_encode([
126
            'status' => 1,
127
            'data' => $data,
128
            'leftCount' => $count
129
        ]);
130
    }
131
132
    /**
133
     * List answers by comment id as json object
134
     * @param int $commentId
135
     * @return string
136
     * @throws ForbiddenException
137
     * @throws NotFoundException
138
     */
139
    public function actionShowanswers($commentId)
140
    {
141
        $this->setJsonHeader();
142
        // check input data
143
        if (!Obj::isLikeInt($commentId) || (int)$commentId < 1) {
144
            throw new ForbiddenException('Input data is incorrect');
145
        }
146
147
        // get configs
148
        $configs = AppRecord::getConfigs('widget', 'Comments');
149
150
        // get data from db by comment id
151
        $records = CommentAnswer::where('comment_id', '=', $commentId);
152 View Code Duplication
        if ((int)$configs['onlyLocale'] === 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
153
            $records = $records->where('lang', '=', App::$Request->getLanguage());
154
        }
155
156
        // check objects count
157
        if ($records->count() < 1) {
158
            throw new NotFoundException(__('No answers for comment is founded'));
159
        }
160
161
        // prepare output
162
        $response = [];
163
        foreach ($records->get() as $row) {
164
            $commentAnswer = new EntityCommentData($row);
165
            $response[] = $commentAnswer->make();
166
        }
167
168
        return json_encode([
169
            'status' => 1,
170
            'data' => $response
171
        ]);
172
    }
173
    
174
    /**
175
     * Get commentaries count for pathway. Pathway should be array [itemId => pathway]
176
     * @throws NativeException
177
     * @return string
178
     */
179
    public function actionCount()
180
    {
181
        // set headers
182
        $this->setJsonHeader();
183
        // get configs
184
        $configs = AppRecord::getConfigs('widget', 'Comments');
185
        // get path array from request
186
        $path = App::$Request->query->get('path');
187
        if (!Obj::isArray($path) || count($path) < 1) {
188
            throw new NativeException('Wrong query params');
189
        }
190
        
191
        $count = [];
192
        // for each item in path array calculate comments count
193
        foreach ($path as $id => $uri) {
194
            $query = CommentPost::where('pathway', '=', $uri);
195
            // check if comments is depend of language locale
196
            if ((int)$configs['onlyLocale'] === 1) {
197
                $query = $query->where('lang', '=', App::$Request->getLanguage());
198
            }
199
            // set itemId => count
200
            $count[(int)$id] = $query->count();
201
        }
202
        // render json response
203
        return json_encode(['status' => 1, 'count' => $count]);
204
    }
205
}