ProductCategoryController   A
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 232
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 108
c 2
b 0
f 1
dl 0
loc 232
rs 9.2
wmc 40

17 Methods

Rating   Name   Duplication   Size   Complexity  
A store() 0 4 1
A create() 0 3 1
B index() 0 63 10
A editSeo() 0 3 1
A tree() 0 3 1
A ajaxCategory() 0 4 2
A generateInput() 0 11 3
A edit() 0 3 1
B ajaxMoveNode() 0 33 6
A update() 0 4 1
A ajaxCategories() 0 7 2
A ajaxChildrenTree() 0 19 3
A destroy() 0 7 2
A changeActive() 0 4 1
A editHighlight() 0 4 1
A refactorAllImages() 0 4 1
A ajaxRootTree() 0 19 3

How to fix   Complexity   

Complex Class

Complex classes like ProductCategoryController 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.

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 ProductCategoryController, and based on these observations, apply Extract Interface, too.

1
<?php namespace App\Http\Controllers\Backend;
2
3
/**
4
 * ProductCategoryController
5
 *
6
 * This is the controller of the product categories of the shop
7
 * @author Matthijs Neijenhuijs <[email protected]>
8
 * @version 0.1
9
 */
10
11
use App\Http\Controllers\Controller;
12
use Dutchbridge\Datatable\ProductCategoryDatatable;
0 ignored issues
show
Bug introduced by
The type Dutchbridge\Datatable\ProductCategoryDatatable was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use Hideyo\Ecommerce\Framework\Services\Product\ProductFacade as ProductService;
14
use Hideyo\Ecommerce\Framework\Services\ProductCategory\ProductCategoryFacade as ProductCategoryService;
15
use Illuminate\Http\Request;
16
use DataTables;
17
use Form;
18
19
class ProductCategoryController extends Controller
20
{
21
    public function index(Request $request)
22
    {
23
        if ($request->wantsJson()) {
24
25
            $productCategory = ProductCategoryService::getModel()->where('shop_id', '=', auth('hideyobackend')->user()->selected_shop_id);
0 ignored issues
show
Bug introduced by
Accessing selected_shop_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
26
            
27
            $datatables = DataTables::of($productCategory)
28
29
            ->addColumn('image', function ($productCategory) {
30
                if ($productCategory->productCategoryImages->count()) {
31
                    return '<img src="/files/product_category/100x100/'.$productCategory->id.'/'.$productCategory->productCategoryImages->first()->file.'"  />';
32
                }
33
            })
34
35
            ->addColumn('title', function ($productCategory) {
36
37
                $categoryTitle = $productCategory->title;
38
                if ($productCategory->refProductCategory) {
39
                    $categoryTitle = '<strong>Redirect:</strong> '.$productCategory->title.' &#8594; '.$productCategory->refProductCategory->title;
40
                } elseif ($productCategory->isRoot()) {
41
                    $categoryTitle = '<strong>Root:</strong> '.$productCategory->title;
42
                } elseif ($productCategory->isChild()) {
43
                    $categoryTitle = '<strong>Child:</strong> '.$productCategory->title;
44
                }
45
                
46
                return $categoryTitle;
47
            })
48
49
            ->addColumn('products', function ($productCategory) {
50
                return $productCategory->products->count();
51
            })
52
            ->addColumn('parent', function ($productCategory) {
53
             
54
                if ($productCategory->parent()->count()) {
55
                    return $productCategory->parent()->first()->title;
56
                }
57
            })
58
59
            ->addColumn('active', function ($product) {
60
                if ($product->active) {
61
                    return '<a href="#" class="change-active" data-url="/admin/product-category/change-active/'.$product->id.'"><span class="glyphicon glyphicon-ok icon-green"></span></a>';
62
                }
63
                
64
                return '<a href="#" class="change-active" data-url="/admin/product-category/change-active/'.$product->id.'"><span class="glyphicon glyphicon-remove icon-red"></span></a>';
65
            })
66
67
68
            ->addColumn('seo', function ($productCategory) {
69
                if ($productCategory->meta_title && $productCategory->meta_description) {
70
                    return '<i class="fa fa-check"></i>';
71
                }
72
            })
73
            ->addColumn('action', function ($productCategory) {
74
                $deleteLink = Form::deleteajax(url()->route('product-category.destroy', $productCategory->id), 'Delete', '', array('class'=>'btn btn-sm btn-danger'), $productCategory->title);
75
                $links = '<a href="'.url()->route('product-category.edit', $productCategory->id).'" class="btn btn-sm btn-success"><i class="entypo-pencil"></i>Edit</a>  '.$deleteLink;
76
            
77
                return $links;
78
            });
79
80
            return $datatables->rawColumns(['active', 'title', 'action'])->make(true);
81
        }
82
        
83
        return view('backend.product_category.index')->with(array('productCategory' =>  ProductCategoryService::selectAll()));
84
    }
85
86
    public function refactorAllImages()
87
    {
88
        $this->productCategoryImage->refactorAllImagesByShopId(auth('hideyobackend')->user()->selected_shop_id);
0 ignored issues
show
Bug introduced by
Accessing selected_shop_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug Best Practice introduced by
The property productCategoryImage does not exist on App\Http\Controllers\Bac...oductCategoryController. Did you maybe forget to declare it?
Loading history...
89
        return redirect()->route('product-category.index');
90
    }
91
92
    public function tree()
93
    {
94
        return view('backend.product_category.tree')->with(array('productCategory' =>  ProductCategoryService::selectAll(), 'tree' => ProductCategoryService::entireTreeStructure(auth('hideyobackend')->user()->shop->id)->toArray()));
0 ignored issues
show
Bug introduced by
Accessing shop on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
95
    }
96
97
    public function ajaxCategories(Request $request)
98
    {
99
        $query = $request->get('q');
100
        $selectedId = $request->get('selectedId');
101
102
        if ($request->wantsJson()) {
103
            return response()->json(ProductCategoryService::ajaxSearchByTitle($query, $selectedId));
104
        }
105
    }
106
107
    public function ajaxCategory(Request $request, $productCategoryId)
108
    {
109
        if ($request->wantsJson()) {
110
            return response()->json(ProductCategoryService::find($productCategoryId));
111
        }
112
    }
113
114
    public function generateInput($array)
115
    {      
116
        if (empty($array['redirect_product_category_id'])) {
117
            $array['redirect_product_category_id'] = null;
118
        }
119
120
        if (empty($array['parent_id'])) {
121
            $array['parent_id'] = null;
122
        }
123
124
        return $array;
125
    }
126
127
    public function create()
128
    {
129
        return view('backend.product_category.create')->with(array('categories' => ProductCategoryService::selectAll()->pluck('title', 'id')));
130
    }
131
132
    public function store(Request $request)
133
    {
134
        $result  = ProductCategoryService::create($this->generateInput($request->all()));
135
        return ProductCategoryService::notificationRedirect('product-category.index', $result, 'The product category was inserted.');
136
    }
137
138
    public function edit($productCategoryId)
139
    {
140
        return view('backend.product_category.edit')->with(array('productCategory' => ProductCategoryService::find($productCategoryId), 'categories' => ProductCategoryService::selectAll()->pluck('title', 'id')));
141
    }
142
143
    public function editHighlight($productCategoryId)
144
    {
145
        $products = ProductService::selectAll()->pluck('title', 'id');
146
        return view('backend.product_category.edit-highlight')->with(array('products' => $products, 'productCategory' => ProductCategoryService::find($productCategoryId), 'categories' => ProductCategoryService::selectAll()->pluck('title', 'id')));
147
    }
148
149
    public function editSeo($productCategoryId)
150
    {
151
        return view('backend.product_category.edit_seo')->with(array('productCategory' => ProductCategoryService::find($productCategoryId), 'categories' => ProductCategoryService::selectAll()->pluck('title', 'id')));
152
    }
153
154
    public function update(Request $request, $productCategoryId)
155
    {
156
        $result  = ProductCategoryService::updateById($this->generateInput($request->all()), $productCategoryId);
157
        return ProductCategoryService::notificationRedirect('product-category.index', $result, 'The product category was updated.');
158
    }
159
160
    public function destroy($productCategoryId)
161
    {
162
        $result  = ProductCategoryService::destroy($productCategoryId);
163
164
        if ($result) {
165
            flash('Category was deleted.');
166
            return redirect()->route('product-category.index');
167
        }
168
    }
169
170
    public function ajaxRootTree()
171
    {
172
        $tree = ProductCategoryService::entireTreeStructure(auth('hideyobackend')->user()->shop->id);
0 ignored issues
show
Bug introduced by
Accessing shop on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
173
        foreach ($tree as $key => $row) {
174
            $children = false;
175
            if ($row->children->count()) {
176
                $children = true;
177
            }
178
179
            $treeData[] = array(
180
                'id' => $row->id,
181
                'text' => $row->title,
182
                'children' => $children,
183
                'type' => 'root'
184
185
            );
186
        }
187
188
        return response()->json($treeData);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $treeData seems to be defined by a foreach iteration on line 173. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
189
    }
190
191
    public function ajaxChildrenTree(Request $request)
192
    {
193
        $productCategoryId = $request->get('id');
194
        $category = ProductCategoryService::find($productCategoryId);
195
196
        foreach ($category->children()->get() as $key => $row) {
197
            $children = false;
198
            if ($row->children->count()) {
199
                $children = true;
200
            }
201
202
            $treeData[] = array(
203
                'id' => $row->id,
204
                'text' => $row->title,
205
                'children' => $children
206
            );
207
        }
208
209
        return response()->json($treeData);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $treeData seems to be defined by a foreach iteration on line 196. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
210
    }
211
212
    public function changeActive($productCategoryId)
213
    {
214
        $result = ProductCategoryService::changeActive($productCategoryId);
215
        return response()->json($result);
216
    }
217
218
    public function ajaxMoveNode(Request $request)
219
    {
220
        $productCategoryId = $request->get('id');
221
        $position = $request->get('position');
222
        $node = ProductCategoryService::find($productCategoryId);
223
        $parent = $request->get('parent');
224
225
        if ($parent != '#') {
226
            $parent = ProductCategoryService::find($parent);
227
            if ($position == 0) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $position of type mixed|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
228
                $node->makeFirstChildOf($parent);
229
            } elseif ($parent->children()->count()) {
230
                $node->makeLastChildOf($parent);
231
                foreach ($parent->children()->get() as $key => $row) {
232
                    $positionKey =  $position - 1;
233
                    if ($key == $positionKey) {
234
                        $node->moveToRightOf($row);
235
                    }
236
                }
237
            } else {
238
                $node->makeFirstChildOf($parent);
239
            }
240
        } else {
241
            $node->makeRoot();
242
        }
243
244
        $node = ProductCategoryService::find($productCategoryId);
245
        $arrayPosition = $node->siblingsAndSelf()->get()->toArray();
246
247
        $positionToMove = $arrayPosition[$position];
248
        
249
        $otherNode = ProductCategoryService::find($positionToMove['id']);
250
        $node->moveToLeftOf($otherNode);
251
    }
252
}
253