OrderController::postDownloadPrint()   B
last analyzed

Complexity

Conditions 10
Paths 9

Size

Total Lines 57
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 10
eloc 35
c 2
b 0
f 1
nc 9
nop 1
dl 0
loc 57
rs 7.6666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace App\Http\Controllers\Backend;
2
3
/**
4
 * OrderController
5
 *
6
 * This is the controller of the product weight types of the shop
7
 * @author Matthijs Neijenhuijs <[email protected]>
8
 * @version 0.1
9
 */
10
11
use App\Http\Controllers\Controller;
12
use Dutchbridge\Services\AssembleOrder;
0 ignored issues
show
Bug introduced by
The type Dutchbridge\Services\AssembleOrder 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\Client\ClientFacade as ClientService;
14
use Hideyo\Ecommerce\Framework\Services\Order\OrderFacade as OrderService;
15
use Hideyo\Ecommerce\Framework\Services\Order\OrderStatusFacade as OrderStatusService;
16
use Hideyo\Ecommerce\Framework\Services\PaymentMethod\PaymentMethodFacade as PaymentMethodService;
17
use Hideyo\Ecommerce\Framework\Services\SendingMethod\SendingMethodFacade as SendingMethodService;use Hideyo\Ecommerce\Framework\Services\Product\ProductFacade as ProductService;
18
use Illuminate\Http\Request;
19
use Carbon\Carbon;
20
use Hideyo\Ecommerce\Framework\Services\Order\Events\OrderChangeStatus;
21
use Event;
22
use Excel;
0 ignored issues
show
Bug introduced by
The type Excel 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...
23
use PDF;
24
25
class OrderController extends Controller
26
{
27
    public function index(Request $request)
28
    {
29
        $shop  = auth('hideyobackend')->user()->shop;
0 ignored issues
show
Unused Code introduced by
The assignment to $shop is dead and can be removed.
Loading history...
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...
30
        $now = Carbon::now();
0 ignored issues
show
Unused Code introduced by
The assignment to $now is dead and can be removed.
Loading history...
31
32
        $revenueThisMonth = null;
33
34
        if ($request->wantsJson()) {
35
36
            $order = OrderService::getModel()
37
                ->from('order as order')
38
                ->select(
39
                [
40
                'order.id',
41
                'order.created_at',
42
                'order.generated_custom_order_id',
43
                'order.order_status_id',
44
                'order.client_id',
45
                'order.delivery_order_address_id',
46
                'order.bill_order_address_id',
47
                'order.price_with_tax']
48
            )->with(array('orderStatus', 'orderPaymentMethod', 'orderSendingMethod', 'products', 'client', 'orderBillAddress', 'orderDeliveryAddress'))->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...
49
50
51
52
            ->leftJoin('order_address', 'order.bill_order_address_id', '=', 'order_address.id');
53
            
54
            
55
            $datatables = \DataTables::of($order)
56
57
            ->addColumn('generated_custom_order_id', function ($order) {
58
                return $order->generated_custom_order_id;
59
            })
60
61
            ->addColumn('created_at', function ($order) {
62
                return date('d F H:i', strtotime($order->created_at));
63
            })
64
65
            ->addColumn('status', function ($order) {
66
                if ($order->orderStatus) {
67
                    if ($order->orderStatus->color) {
68
                        return '<a href="/admin/order/'.$order->id.'" style="text-decoration:none;"><span style="background-color:'.$order->orderStatus->color.'; padding: 10px; line-height:30px; text-align:center; color:white;">'.$order->orderStatus->title.'</span></a>';
69
                    }
70
                    return $order->orderStatus->title;
71
                }
72
            })
73
74
            ->filterColumn('client', function ($query, $keyword) {
75
76
                $query->where(
77
                    function ($query) use ($keyword) {
78
                        $query->whereRaw("order_address.firstname like ?", ["%{$keyword}%"]);
79
                        $query->orWhereRaw("order_address.lastname like ?", ["%{$keyword}%"]);
80
                        ;
81
                    }
82
                );
83
            })
84
            ->addColumn('client', function ($order) {
85
                if ($order->client) {
86
                    if ($order->orderBillAddress) {
87
                        return '<a href="/admin/client/'.$order->client_id.'/order">'.$order->orderBillAddress->firstname.' '.$order->orderBillAddress->lastname.' ('.$order->client->orders->count() .')</a>';
88
                    }
89
                }
90
            })
91
            ->addColumn('products', function ($order) {
92
                if ($order->products) {
93
                    return $order->products->count();
94
                }
95
            })
96
            ->addColumn('price_with_tax', function ($order) {
97
                $money = '&euro; '.$order->getPriceWithTaxNumberFormat();
98
                return $money;
99
            })
100
101
102
            ->addColumn('paymentMethod', function ($order) {
103
                if ($order->orderPaymentMethod) {
104
                    return $order->orderPaymentMethod->title;
105
                }
106
            })
107
            ->addColumn('sendingMethod', function ($order) {
108
                if ($order->orderSendingMethod) {
109
                    return $order->orderSendingMethod->title;
110
                }
111
            })
112
            ->addColumn('action', function ($order) {
113
                $deleteLink = \Form::deleteajax('/admin/order/'. $order->id, 'Delete', '', array('class'=>'btn btn-default btn-sm btn-danger'));
0 ignored issues
show
Unused Code introduced by
The assignment to $deleteLink is dead and can be removed.
Loading history...
114
                $download = '<a href="/admin/order/'.$order->id.'/download" class="btn btn-default btn-sm btn-info"><i class="entypo-pencil"></i>Download</a>  ';
115
            
116
       
117
                
118
                $links = '<a href="/admin/order/'.$order->id.'" class="btn btn-default btn-sm btn-success"><i class="entypo-pencil"></i>Show</a>  '.$download;
119
            
120
                return $links;
121
            });
122
123
            return $datatables->rawColumns(['status', 'client', 'action'])->make(true);
124
        }
125
        
126
        return view('backend.order.index')->with(array('revenueThisMonth' => $revenueThisMonth, 'order' => OrderService::selectAll())); 
127
    }
128
129
    public function getPrintOrders(Request $request)
130
    {
131
        $orders = $request->session()->get('print_orders');
132
        return view('admin.order.print-orders')->with(array('orders' => $orders));
133
    }
134
135
    public function getPrint()
136
    {
137
        return view('backend.order.print')->with(array('orderStatuses' => OrderStatusService::selectAll()->pluck('title', 'id')));
138
    }
139
    
140
    public function postDownloadPrint(Request $request)
141
    {
142
        $data = $request->all();
143
144
        if ($data and $data['order']) {
145
146
            if($data['type'] == 'one-pdf') {
147
                $pdfHtml = "";
148
                $countOrders = count($data['order']);
149
                $i = 0;
150
                foreach ($data['order'] as $key => $val) {
151
                    $i++;
152
153
                    $order = OrderService::find($val);
154
                    $text = $this->sendingPaymentMethodRelated->selectOneByPaymentMethodIdAndSendingMethodIdAdmin($order->orderSendingMethod->sending_method_id, $order->orderPaymentMethod->payment_method_id);
0 ignored issues
show
Bug Best Practice introduced by
The property sendingPaymentMethodRelated does not exist on App\Http\Controllers\Backend\OrderController. Did you maybe forget to declare it?
Loading history...
155
                    
156
                    $pdfText = "";
157
                    if ($text) {
158
                        $pdfText = $this->replaceTags($text->pdf_text, $order);
159
                    }
160
                    
161
                    $pdfHtml .= view('admin.order.bodypdf', array('order' => $order, 'pdfText' => $pdfText))->render();
162
                   
163
                    if ($i != $countOrders) {
164
                        $pdfHtml .= '<div style="page-break-before: always;"></div>';
165
                    }
166
                }
167
168
                $pdfHtmlBody = view('admin.order.multiplepdfbody', array('body' => $pdfHtml))->render();
169
                $pdf = PDF::loadHTML($pdfHtmlBody);
170
171
                return $pdf->download('order-'.$order->generated_custom_order_id.'.pdf');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $order seems to be defined by a foreach iteration on line 150. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
172
            } elseif($data['type'] == 'product-list') {
173
                $products = OrderService::productsByOrderIds($data['order']);
174
175
                if($products) {
176
177
178
                    Excel::create('products', function ($excel) use ($products) {
179
180
                        $excel->sheet('Products', function ($sheet) use ($products) {
181
                            $newArray = array();
182
                            foreach ($products as $key => $row) {
183
                
184
                                $newArray[$row->title] = array(
185
                                    'total' => $row->total_amount,
186
                                    'title' => $row->title,
187
                                    'reference_code' => $row->reference_code,
188
                                    'price_with_tax' => $row->price_with_tax,
189
                                    'price_without_tax' => $row->price_without_tax
190
                                );
191
                            }
192
193
                                ksort($newArray);
194
                            $sheet->fromArray($newArray);
195
                        });
196
                    })->download('xls');
197
198
                }
199
            }
200
        }
201
    }
202
203
    public function postPrint(Request $request)
204
    {
205
        $data = $request->all();
206
207
        $orders = OrderService::selectAllByShopIdAndStatusId($data['order_status_id'], $data['start_date'], $data['end_date']);
208
209
        if ($orders) {
210
            $request->session()->put('print_orders', $orders->toArray());
211
            return response()->json(array('orders' => $orders->toArray() ));
212
        }
213
214
        $request->session()->destroy('print_orders');
0 ignored issues
show
Bug introduced by
The method destroy() does not exist on Illuminate\Session\Store. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

214
        $request->session()->/** @scrutinizer ignore-call */ destroy('print_orders');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
215
        return response()->json(false);
216
    }
217
218
    public function show($orderId)
219
    {
220
        $order = OrderService::find($orderId);
221
        return view('backend.order.show')->with(array('order' => $order, 'orderStatuses' => OrderStatusService::selectAll()->pluck('title', 'id')));
222
    }
223
224
    public function updateStatus(Request $request, $orderId)
225
    {
226
        $orderStatusId = $request->get('order_status_id');
227
        if ($orderStatusId) {
228
            $result = OrderService::updateStatus($orderId, $orderStatusId);
229
            Event::dispatch(new OrderChangeStatus($result));
0 ignored issues
show
Bug introduced by
The method dispatch() does not exist on Event. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

229
            Event::/** @scrutinizer ignore-call */ 
230
                   dispatch(new OrderChangeStatus($result));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
230
            \flash('The status was updated to '.$result->OrderStatus->title);
231
        }
232
233
        return redirect()->route('order.show', $orderId);
234
    }
235
236
    public function download($orderId)
237
    {
238
        $order = OrderService::find($orderId);
239
        $text = $this->sendingPaymentMethodRelated->selectOneByPaymentMethodIdAndSendingMethodIdAdmin($order->orderSendingMethod->sending_method_id, $order->orderPaymentMethod->payment_method_id);
0 ignored issues
show
Bug Best Practice introduced by
The property sendingPaymentMethodRelated does not exist on App\Http\Controllers\Backend\OrderController. Did you maybe forget to declare it?
Loading history...
240
        
241
        $pdfText = "";
242
        if ($text) {
243
            $pdfText = $this->replaceTags($text->pdf_text, $order);
244
        }
245
        $pdf = PDF::loadview('backend.order.pdf', array('order' => $order, 'pdfText' => $pdfText));
246
247
        return $pdf->download('order-'.$order->generated_custom_order_id.'.pdf');
248
    }
249
250
251
    public function downloadLabel($orderId)
252
    {
253
        $order = OrderService::find($orderId);
254
        if($order->orderLabel()->count()) {
255
          header("Content-type: application/octet-stream");
256
          header("Content-disposition: attachment;filename=label.pdf");
257
          echo $order->orderLabel->data;
258
        }
259
    }
260
261
    public function replaceTags($content, $order)
262
    {
263
264
        $replace = array(
265
            'orderId' => $order->generated_custom_order_id,
266
            'orderCreated' => $order->created_at,
267
            'orderTotalPriceWithTax' => $order->getPriceWithTaxNumberFormat(),
268
            'orderTotalPriceWithoutTax' => $order->getPriceWithoutTaxNumberFormat(),
269
            'clientEmail' => $order->client->email,
270
            'clientFirstname' => $order->orderBillAddress->firstname,
271
            'clientLastname' => $order->orderBillAddress->lastname,
272
            'clientCompany' => $order->orderBillAddress->company,
273
            'clientDeliveryFirstname' => $order->orderDeliveryAddress->firstname,
274
            'clientDeliveryLastname' => $order->orderDeliveryAddress->lastname,
275
            'clientDeliveryStreet' => $order->orderDeliveryAddress->street,
276
            'clientDeliveryHousenumber' => $order->orderDeliveryAddress->housenumber,
277
            'clientDeliveryHousenumberSuffix' => $order->orderDeliveryAddress->housenumber_suffix,
278
            'clientDeliveryZipcode' => $order->orderDeliveryAddress->zipcode,
279
            'clientDeliveryCity' => $order->orderDeliveryAddress->city,
280
            'clientDeliveryCountry' => $order->orderDeliveryAddress->country,
281
            'clientDeliveryCompany' => $order->orderDeliveryAddress->company
282
        );
283
        foreach ($replace as $key => $val) {
284
            $content = str_replace("[" . $key . "]", $val, $content);
285
        }
286
287
        return $content;
288
    }
289
290
    public function edit($orderId)
291
    {
292
        return view('backend.order.edit')->with(array('order' => OrderService::find($orderId)));
293
    }
294
295
    public function update(Request $request, $orderId)
296
    {
297
        $result  = OrderService::updateById($request->all(), $orderId);
298
299
        if ($result->errors()->all()) {
300
            return redirect()->back()->withInput()->withErrors($result->errors()->all());
301
        } else {
302
            flash('The order was updated.');
303
            return redirect()->route('admin.order.index');
304
        }
305
    }
306
}
307