Passed
Push — master ( b7618a...8c3cc9 )
by Mihail
15:19
created

Content   D

Complexity

Total Complexity 42

Size/Duplication

Total Lines 281
Duplicated Lines 44.84 %

Coupling/Cohesion

Components 1
Dependencies 22

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 42
c 4
b 0
f 0
lcom 1
cbo 22
dl 126
loc 281
rs 4.8358

9 Methods

Rating   Name   Duplication   Size   Complexity  
B actionIndex() 0 36 3
B actionUpdate() 28 28 5
C actionDelete() 24 24 7
C actionRestore() 26 26 7
B actionClear() 0 26 5
A actionCategories() 0 4 1
C actionCategorydelete() 28 28 7
B actionCategoryupdate() 0 26 4
A actionSettings() 20 20 3

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Content often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Content, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Apps\Controller\Admin;
4
5
use Apps\ActiveRecord\ContentCategory;
6
use Apps\Model\Admin\Content\FormCategoryDelete;
7
use Apps\Model\Admin\Content\FormCategoryUpdate;
8
use Apps\Model\Admin\Content\FormContentClear;
9
use Apps\Model\Admin\Content\FormContentDelete;
10
use Apps\Model\Admin\Content\FormContentRestore;
11
use Apps\Model\Admin\Content\FormContentUpdate;
12
use Apps\Model\Admin\Content\FormSettings;
13
use Extend\Core\Arch\AdminAppController;
14
use Ffcms\Core\App;
15
use Apps\ActiveRecord\Content as ContentEntity;
16
use Ffcms\Core\Exception\ForbiddenException;
17
use Ffcms\Core\Exception\NotFoundException;
18
use Ffcms\Core\Exception\SyntaxException;
19
use Ffcms\Core\Helper\FileSystem\Directory;
20
use Ffcms\Core\Helper\HTML\SimplePagination;
21
use Ffcms\Core\Helper\Type\Obj;
22
23
class Content extends AdminAppController
24
{
25
    const ITEM_PER_PAGE = 10;
26
27
    /**
28
     * List content items
29
     * @throws \Ffcms\Core\Exception\SyntaxException
30
     * @throws \Ffcms\Core\Exception\NativeException
31
     */
32
    public function actionIndex()
33
    {
34
        // set current page and offset
35
        $page = (int)App::$Request->query->get('page');
36
        $offset = $page * self::ITEM_PER_PAGE;
37
38
        $query = null;
0 ignored issues
show
Unused Code introduced by
$query 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...
39
        // get query type (trash, category, all)
40
        $type = App::$Request->query->get('type');
41
        if ($type === 'trash') {
42
            $query = ContentEntity::onlyTrashed();
43
        } elseif (Obj::isLikeInt($type)) { // sounds like category id ;)
44
            $query = ContentEntity::where('category_id', '=', (int)$type);
45
        } else {
46
            $query = new ContentEntity();
47
            $type = 'all';
48
        }
49
50
        // build pagination
51
        $pagination = new SimplePagination([
52
            'url' => ['content/index', null, null, ['type' => $type]],
53
            'page' => $page,
54
            'step' => self::ITEM_PER_PAGE,
55
            'total' => $query->count()
56
        ]);
57
58
        // build listing objects
59
        $records = $query->orderBy('id', 'desc')->skip($offset)->take(self::ITEM_PER_PAGE)->get();
60
61
62
        $this->response = App::$View->render('index', [
63
            'records' => $records,
64
            'pagination' => $pagination,
65
            'type' => $type
66
        ]);
67
    }
68
69
    /**
70
     * Edit and add content items
71
     * @param $id
72
     * @throws \Ffcms\Core\Exception\SyntaxException
73
     * @throws \Ffcms\Core\Exception\NativeException
74
     */
75 View Code Duplication
    public function actionUpdate($id)
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
        // get item with trashed objects
78
        $record = ContentEntity::withTrashed()->find($id);
0 ignored issues
show
Bug introduced by
The method find does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\SoftDeletes.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
79
        $isNew = $record->id === null;
80
81
        // create empty object if its new
82
        if ($isNew === true) {
83
            $record = new ContentEntity();
84
        }
85
86
        // init model
87
        $model = new FormContentUpdate($record);
88
89
        // check if model is submit
90
        if ($model->send() && $model->validate()) {
91
            $model->save();
92
            if ($isNew === true) {
93
                App::$Response->redirect('content/index');
94
            }
95
            App::$Session->getFlashBag()->add('success', __('Content is successful updated'));
96
        }
97
98
        // draw response
99
        $this->response = App::$View->render('content_update', [
100
            'model' => $model
101
        ]);
102
    }
103
104
    /**
105
     * Delete content by id
106
     * @param int $id
107
     * @throws NotFoundException
108
     * @throws \Ffcms\Core\Exception\SyntaxException
109
     * @throws \Ffcms\Core\Exception\NativeException
110
     */
111 View Code Duplication
    public function actionDelete($id)
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...
112
    {
113
        if (!Obj::isLikeInt($id) || $id < 1) {
114
            throw new NotFoundException();
115
        }
116
117
        // get content record and check availability
118
        $record = ContentEntity::find($id);
119
        if ($record === null || $record === false) {
120
            throw new NotFoundException();
121
        }
122
123
        // init delete model
124
        $model = new FormContentDelete($record);
125
        if ($model->send() && $model->validate()) {
126
            $model->make();
127
            App::$Session->getFlashBag()->add('success', __('Content is successful moved to trash'));
128
            App::$Response->redirect('content/index');
129
        }
130
131
        $this->response = App::$View->render('content_delete', [
132
            'model' => $model->export()
133
        ]);
134
    }
135
136
    /**
137
     * Restore deleted content
138
     * @param $id
139
     * @throws NotFoundException
140
     * @throws \Ffcms\Core\Exception\SyntaxException
141
     * @throws \Ffcms\Core\Exception\NativeException
142
     */
143 View Code Duplication
    public function actionRestore($id)
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...
144
    {
145
        if (!Obj::isLikeInt($id) || $id < 1) {
146
            throw new NotFoundException();
147
        }
148
149
        // get removed object
150
        $record = ContentEntity::onlyTrashed()->find($id);
0 ignored issues
show
Bug introduced by
The method find does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\SoftDeletes.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
151
        if ($record === null || $record === false) {
152
            throw new NotFoundException();
153
        }
154
155
        // init model
156
        $model = new FormContentRestore($record);
157
        // check if action is send
158
        if ($model->send() && $model->validate()) {
159
            $model->make();
160
            App::$Session->getFlashBag()->add('success', __('Content are successful recovered'));
161
            App::$Response->redirect('content/index');
162
        }
163
164
        // draw response
165
        $this->response = App::$View->render('content_restore', [
166
            'model' => $model->export()
167
        ]);
168
    }
169
170
    /**
171
     * Clear the trashed items
172
     * @throws SyntaxException
173
     * @throws \Ffcms\Core\Exception\SyntaxException
174
     * @throws \Ffcms\Core\Exception\NativeException
175
     */
176
    public function actionClear()
177
    {
178
        // find trashed rows
179
        $records = ContentEntity::onlyTrashed();
180
181
        // init model
182
        $model = new FormContentClear($records->count());
183
        if ($model->send() && $model->validate()) {
184
            // remove all trashed items
185
            foreach ($records->get() as $item) {
0 ignored issues
show
Bug introduced by
The method get does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\SoftDeletes.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
186
                $galleryPath = '/upload/gallery/' . (int)$item->id;
187
                if (Directory::exist($galleryPath)) {
188
                    Directory::remove($galleryPath);
189
                }
190
            }
191
            // totally remove rows from db
192
            $records->forceDelete();
193
            App::$Session->getFlashBag()->add('success', __('Trashed content is cleanup'));
194
            App::$Response->redirect('content/index');
195
        }
196
197
        // draw response
198
        $this->response = App::$View->render('content_clear', [
199
            'model' => $model->export()
200
        ]);
201
    }
202
203
    /**
204
     * Display category list
205
     */
206
    public function actionCategories()
207
    {
208
        $this->response = App::$View->render('category_list');
209
    }
210
211
    /**
212
     * Delete category action
213
     * @param int $id
214
     * @throws ForbiddenException
215
     * @throws \Ffcms\Core\Exception\SyntaxException
216
     * @throws \Ffcms\Core\Exception\NativeException
217
     */
218 View Code Duplication
    public function actionCategorydelete($id)
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...
219
    {
220
        // check id
221
        if (!Obj::isLikeInt($id) || $id < 2) {
222
            throw new ForbiddenException();
223
        }
224
225
        // get object relation
226
        $record = ContentCategory::find($id);
227
        if ($record === null || $record === false) {
228
            throw new ForbiddenException();
229
        }
230
231
        // init model with object relation
232
        $model = new FormCategoryDelete($record);
233
234
        // check if delete is submited
235
        if ($model->send() && $model->validate()) {
236
            $model->make();
237
            App::$Session->getFlashBag()->add('success', __('Category is successful removed'));
238
            App::$Response->redirect('content/categories');
239
        }
240
241
        // draw view
242
        $this->response = App::$View->render('category_delete', [
243
            'model' => $model->export()
244
        ]);
245
    }
246
247
    /**
248
     * Show category edit and create
249
     * @param null $id
250
     * @throws \Ffcms\Core\Exception\SyntaxException
251
     * @throws \Ffcms\Core\Exception\NativeException
252
     */
253
    public function actionCategoryupdate($id = null)
254
    {
255
        // get owner id for new rows
256
        $parentId = (int)App::$Request->query->get('parent');
257
258
        // get relation and pass to model
259
        $record = ContentCategory::findOrNew($id);
260
        $isNew = $record->id === null;
261
        $model = new FormCategoryUpdate($record, $parentId);
0 ignored issues
show
Documentation introduced by
$record is of type object<Illuminate\Suppor...atabase\Eloquent\Model>, but the function expects a object<Apps\ActiveRecord\ContentCategory>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
262
263
        // if model is submited
264
        if ($model->send() && $model->validate()) {
265
            $model->save();
266
            // if is new - redirect to list after submit
267
            if ($isNew) {
268
                App::$Response->redirect('content/categories');
269
            }
270
            // show notify message
271
            App::$Session->getFlashBag()->add('success', __('Category is successful updated'));
272
        }
273
274
        // draw response view and pass model properties
275
        $this->response = App::$View->render('category_update', [
276
            'model' => $model->export()
277
        ]);
278
    }
279
280
    /**
281
     * Content app settings
282
     */
283 View Code Duplication
    public function actionSettings()
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...
284
    {
285
        // init model with config array data
286
        $model = new FormSettings($this->getConfigs());
287
288
        // check if form is send
289
        if ($model->send()) {
290
            if ($model->validate()) {
291
                $this->setConfigs($model->getAllProperties());
292
                App::$Response->redirect('content/index');
293
            } else {
294
                App::$Session->getFlashBag()->add('error', __('Form validation is failed'));
295
            }
296
        }
297
298
        // draw response
299
        $this->response = App::$View->render('settings', [
300
            'model' => $model->export()
301
        ]);
302
    }
303
}