Passed
Push — master ( c26e61...c33b65 )
by Matthijs
14:28 queued 08:02
created

CheckoutController::postComplete()   C

Complexity

Conditions 15
Paths 114

Size

Total Lines 62
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 36
nc 114
nop 1
dl 0
loc 62
rs 5.8
c 0
b 0
f 0

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\Frontend;
2
3
use App\Http\Controllers\Controller;
4
use Illuminate\Http\Request;
5
use Hideyo\Ecommerce\Framework\Services\Sendingmethod\SendingmethodFacade as SendingmethodService;
6
use Hideyo\Ecommerce\Framework\Services\PaymentMethod\PaymentMethodFacade as PaymentMethodService;
7
use Hideyo\Ecommerce\Framework\Services\Order\OrderFacade as OrderService;
8
use Hideyo\Ecommerce\Framework\Services\Order\Events\OrderChangeStatus;
9
use Cart;
10
use Validator;
11
use Notification;
12
use BrowserDetect;
13
14
class CheckoutController extends Controller
15
{
16
    /**
17
     * Create a new controller instance.
18
     *
19
     * @return void
20
     */
21
    public function __construct(
22
        Request $request)
23
    {
24
        $this->request = $request;
0 ignored issues
show
Bug Best Practice introduced by
The property request does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
25
    }
26
27
    public function checkout()
28
    {
29
        $sendingMethodsList = SendingMethodService::selectAllActiveByShopId(config()->get('app.shop_id'));
30
31
        if (Cart::getContent()->count()) {
32
33
            $paymentMethodsList = Cart::getConditionsByType('sending_method')->first()->getAttributes()['data']['related_payment_methods_list'];
34
         
35
            if(!Cart::getConditionsByType('sending_method')->count()) {
36
                Notification::error('Selecteer een verzendwijze');
37
                return redirect()->to('cart');
38
            }
39
40
            if(!Cart::getConditionsByType('payment_method')->count()) {
41
42
                Notification::error('Selecteer een betaalwijze');
43
                return redirect()->to('cart');
44
            }
45
46
        } else {
47
            return redirect()->to('cart');
48
        }
49
50
51
52
        if (auth('web')->guest()) {
53
            $noAccountUser = session()->get('noAccountUser');
54
            if ($noAccountUser) {
55
                if (!isset($noAccountUser['delivery'])) {
56
                    $noAccountUser['delivery'] = $noAccountUser;
57
                    session()->put('noAccountUser', $noAccountUser);
58
                }
59
  
60
                return view('frontend.checkout.no-account')->with(array( 
61
                    'noAccountUser' =>  $noAccountUser, 
62
                    'sendingMethodsList' => $sendingMethodsList, 
63
                    'paymentMethodsList' => $paymentMethodsList));
64
            }
65
              
66
             return view('frontend.checkout.login')->with(array(  'sendingMethodsList' => $sendingMethodsList, 'paymentMethodsList' => $paymentMethodsList));
67
        }
68
69
        $user = auth('web')->user();
70
        self::checkCountryPrice($user->clientDeliveryAddress->country);
0 ignored issues
show
Bug introduced by
The method checkCountryPrice() does not exist on App\Http\Controllers\Frontend\CheckoutController. ( Ignorable by Annotation )

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

70
        self::/** @scrutinizer ignore-call */ 
71
              checkCountryPrice($user->clientDeliveryAddress->country);

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...
Bug introduced by
Accessing clientDeliveryAddress on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
71
72
        if (!$user->clientDeliveryAddress()->count()) {
0 ignored issues
show
Bug introduced by
The method clientDeliveryAddress() does not exist on Illuminate\Contracts\Auth\Authenticatable. It seems like you code against a sub-type of Illuminate\Contracts\Auth\Authenticatable such as Illuminate\Foundation\Auth\User. ( Ignorable by Annotation )

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

72
        if (!$user->/** @scrutinizer ignore-call */ clientDeliveryAddress()->count()) {
Loading history...
73
            ClientService::setBillOrDeliveryAddress(config()->get('app.shop_id'), $user->id, $user->clientBillAddress->id, 'delivery');
0 ignored issues
show
Bug introduced by
Accessing clientBillAddress on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
The type App\Http\Controllers\Frontend\ClientService 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...
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
74
            return redirect()->to('cart/checkout');
75
        }
76
77
        return view('frontend.checkout.index')->with(array(
78
            'user' =>  $user, 
79
            'sendingMethodsList' => $sendingMethodsList, 
80
            'paymentMethodsList' => $paymentMethodsList));
81
    }
82
83
84
    public function postCheckoutLogin(Request $request)
85
    {
86
        // create the validation rules ------------------------
87
        $rules = array(
88
            'email'         => 'required|email',     // required and must be unique in the ducks table
89
            'password'      => 'required'
90
        );
91
92
        $validator = Validator::make($request->all(), $rules);
93
94
        if ($validator->fails()) {
95
96
            foreach ($validator->errors()->all() as $error) {
97
                Notification::error($error);
98
            }
99
100
            return redirect()->to('cart/checkout')
101
            ->withErrors(true, 'login')->withInput();
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type Illuminate\Contracts\Sup...geProvider|string|array expected by parameter $provider of Illuminate\Http\RedirectResponse::withErrors(). ( Ignorable by Annotation )

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

101
            ->withErrors(/** @scrutinizer ignore-type */ true, 'login')->withInput();
Loading history...
102
        }
103
104
        $userdata = array(
105
            'email' => $request->get('email'),
106
            'password' => $request->get('password'),
107
            'confirmed' => 1,
108
            'active' => 1,
109
            'shop_id' => config()->get('app.shop_id')
110
        );
111
112
        /* Try to authenticate the credentials */
113
        if (auth('web')->attempt($userdata)) {
114
            // we are now logged in, go to admin
115
            return redirect()->to('cart/checkout');
116
        }
117
118
        Notification::error(trans('message.error.data-is-incorrect'));
0 ignored issues
show
Bug introduced by
It seems like trans('message.error.data-is-incorrect') can also be of type array; however, parameter $message of Krucas\Notification\Facades\Notification::error() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

118
        Notification::error(/** @scrutinizer ignore-type */ trans('message.error.data-is-incorrect'));
Loading history...
119
        return redirect()->to('cart/checkout')->withErrors(true, 'login')->withInput(); 
120
    }
121
122
    //to-do: transfer logic to repo
123
    public function postCheckoutRegister(Request $request)
124
    {
125
        if (!Cart::getContent()->count()) {  
126
            return redirect()->to('cart/checkout');
127
        }
128
129
        $userdata = $request->all();
130
131
        $rules = array(
132
            'email'         => 'required|email',     // required and must be unique in the ducks table
133
            'password'      => 'required',
134
            'firstname'     => 'required',
135
            'lastname'      => 'required',
136
            'zipcode'       => 'required',
137
            'housenumber'   => 'required|numeric',
138
            'street'        => 'required',
139
            'city'          => 'required'
140
            );
141
142
        if (!$userdata['password']) {
143
            unset($rules['email']);
144
            unset($rules['password']);
145
        } 
146
147
        $validator = Validator::make($request->all(), $rules);
148
149
        if ($validator->fails()) {
150
            // get the error messages from the validator
151
            foreach ($validator->errors()->all() as $error) {
152
                Notification::error($error);
153
            }
154
            // redirect our user back to the form with the errors from the validator
155
            return redirect()->to('cart/checkout')
156
            ->withErrors(true, 'register')->withInput();
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type Illuminate\Contracts\Sup...geProvider|string|array expected by parameter $provider of Illuminate\Http\RedirectResponse::withErrors(). ( Ignorable by Annotation )

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

156
            ->withErrors(/** @scrutinizer ignore-type */ true, 'register')->withInput();
Loading history...
157
        }
158
159
        if ($userdata['password']) {
160
            $registerAttempt = ClientService::validateRegister($userdata, config()->get('app.shop_id'));
161
162
            if ($registerAttempt) {
163
                $register = ClientService::register($userdata, config()->get('app.shop_id'), true);
164
            } else {
165
                $client = ClientService::findByEmail($userdata['email'], config()->get('app.shop_id'));
166
167
                if ($client->account_created) {
168
                    Notification::error('Je hebt al een account. Login aan de linkerkant of vraag een nieuw wachtwoord aan.');
169
                    return redirect()->to('cart/checkout')->withInput()->withErrors('Dit emailadres is al in gebruik. Je kan links inloggen.', 'register');
170
                } else {
171
                    $register = ClientService::createAccount($userdata, config()->get('app.shop_id'));
172
                }
173
            }
174
175
            if ($register) {
176
                $data = $register;
177
                $data['shop'] = app('shop');
178
        
179
                Mail::send('frontend.email.register-mail', array('password' => $userdata['password'], 'user' => $data->toArray(), 'billAddress' => $data->clientBillAddress->toArray()), function ($message) use ($data) {
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\Frontend\Mail was not found. Did you mean Mail? If so, make sure to prefix the type with \.
Loading history...
180
            
181
                    $message->to($data['email'])->from($data['shop']->email, $data['shop']->title)->subject('Je bent geregistreerd.');
182
                });
183
184
                $userdata = array(
185
                    'email' => $request->get('email'),
186
                    'password' => $request->get('password'),
187
                    'confirmed' => 1,
188
                    'active' => 1
189
                );
190
191
                auth('web')->attempt($userdata);
192
193
                return redirect()->to('cart/checkout')->withErrors('Je bent geregistreerd. Er is een bevestigingsmail gestuurd.', 'login');
194
            } else {
195
                Notification::error('Je hebt al een account');
196
                return redirect()->to('cart/checkout')->withErrors(true, 'register')->withInput();
197
            }
198
        }
199
        
200
        unset($userdata['password']);
201
        $registerAttempt = ClientService::validateRegisterNoAccount($userdata, config()->get('app.shop_id'));
202
203
        if ($registerAttempt) {
204
            $register = ClientService::register($userdata, config()->get('app.shop_id'));   
205
            $userdata['client_id'] = $register->id;
206
        } else {
207
            $client = ClientService::findByEmail($userdata['email'], config()->get('app.shop_id'));
208
            if ($client) {
209
                $userdata['client_id'] = $client->id;
210
            }
211
        }
212
213
        session()->put('noAccountUser', $userdata);
214
        return redirect()->to('cart/checkout');
215
       
216
        
217
    }
218
219
    public function postComplete(Request $request)
220
    {
221
        $noAccountUser = session()->get('noAccountUser');
222
        if (auth('web')->guest() and !$noAccountUser) {
223
            return view('frontend.checkout.login');
224
        }
225
226
        if (!Cart::getContent()->count()) {        
227
            return redirect()->to('cart/checkout');
228
        }
229
230
        $data = array(
231
            'products' => Cart::getContent()->toArray(),
232
            'price_with_tax' => Cart::getTotalWithTax(false),
233
            'price_without_tax' => Cart::getTotalWithoutTax(false),
234
            'comments' => $request->get('comments'),
235
            'browser_detect' => serialize(BrowserDetect::toArray())
236
        );
237
238
239
        if (auth('web')->check()) {
240
            $data['user_id'] = auth('web')->user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
241
        } else {
242
            $data['user_id'] = $noAccountUser['client_id'];
243
        }     
244
245
        if(Cart::getConditionsByType('sending_method')->count()) {
246
            $data['sending_method'] = Cart::getConditionsByType('sending_method');
247
        }
248
249
        if(Cart::getConditionsByType('sending_method_country_price')->count()) {
250
            $data['sending_method_country_price'] = Cart::getConditionsByType('sending_method_country_price');
251
        }
252
253
        if(Cart::getConditionsByType('payment_method')->count()) {
254
            $data['payment_method'] = Cart::getConditionsByType('payment_method');
255
        }
256
257
        $orderInsertAttempt = OrderService::createByUserAndShopId($data, config()->get('app.shop_id'), $noAccountUser);
258
259
        if ($orderInsertAttempt AND $orderInsertAttempt->count()) {
260
            if ($orderInsertAttempt->OrderPaymentMethod and $orderInsertAttempt->OrderPaymentMethod->paymentMethod->order_confirmed_order_status_id) {
261
                $orderStatus = OrderService::updateStatus($orderInsertAttempt->id, $orderInsertAttempt->OrderPaymentMethod->paymentMethod->order_confirmed_order_status_id);
262
                if ($orderInsertAttempt->OrderPaymentMethod->paymentMethod->order_confirmed_order_status_id) {
263
                    Event::fire(new OrderChangeStatus($orderStatus));
0 ignored issues
show
Bug introduced by
The type App\Http\Controllers\Frontend\Event was not found. Did you mean Event? If so, make sure to prefix the type with \.
Loading history...
264
                }
265
            }
266
267
            session()->put('orderData', $orderInsertAttempt);
268
269
            if ($orderInsertAttempt->OrderPaymentMethod and $orderInsertAttempt->OrderPaymentMethod->paymentMethod->payment_external) {
270
                return redirect()->to('cart/payment');
271
            }
272
273
            app('cart')->clear();
274
            app('cart')->clearCartConditions();  
275
            session()->flush('noAccountUser');
276
            $body = "";
277
            return view('frontend.checkout.complete')->with(array('body' => $body));            
278
        }
279
280
        return redirect()->to('cart/checkout');
281
    }
282
283
    public function getEditAddress(Request $request, $type) {
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

283
    public function getEditAddress(/** @scrutinizer ignore-unused */ Request $request, $type) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
284
285
        if (!Cart::getContent()->count()) {        
286
            return redirect()->to('cart/checkout');
287
        }              
288
289
        if (auth('web')->guest()) {
290
            $noAccountUser = session()->get('noAccountUser');
291
            if ($noAccountUser) {
292
                
293
                $address = $noAccountUser;
294
                if ($type == 'delivery') {
295
                    $address = $noAccountUser['delivery'];
296
                }
297
298
                return view('frontend.checkout.edit-address-no-account')->with(array('type' => $type, 'noAccountUser' =>  $noAccountUser, 'clientAddress' => $address));
299
            }
300
        }
301
302
        $user = auth('web')->user();
303
304
        if ($type == 'delivery') {
305
            $address = $user->clientDeliveryAddress->toArray();
0 ignored issues
show
Bug introduced by
Accessing clientDeliveryAddress on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
306
        } else {
307
            $address = $user->clientBillAddress->toArray();
0 ignored issues
show
Bug introduced by
Accessing clientBillAddress on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
308
        }
309
310
        return view('frontend.checkout.edit-address')->with(array('type' => $type, 'user' => $user, 'clientAddress' => $address));
311
    }
312
313
    public function postEditAddress(Request $request, $type)
314
    {
315
        if (!Cart::getContent()->count()) {        
316
            return redirect()->to('cart/checkout');
317
        } 
318
        
319
        $userdata = $request->all();
320
321
        // create the validation rules ------------------------
322
        $rules = array(
323
            'firstname'     => 'required',
324
            'lastname'      => 'required',
325
            'zipcode'       => 'required',
326
            'housenumber'   => 'required|numeric',
327
            'street'        => 'required',
328
            'city'          => 'required'
329
        );
330
331
        $validator = Validator::make($request->all(), $rules);
332
333
        if ($validator->fails()) {
334
            // get the error messages from the validator
335
            foreach ($validator->errors()->all() as $error) {
336
                Notification::error($error);
337
            }
338
339
            // redirect our user back to the form with the errors from the validator
340
            return redirect()->to('cart/edit-address/'.$type)
341
            ->with(array('type' => $type))->withInput();
342
        }
343
344
        if (auth('web')->guest()) {
345
            $noAccountUser = session()->get('noAccountUser');
346
            if ($noAccountUser) {
347
                if ($type == 'bill') {
348
                    $noAccountUser = array_merge($noAccountUser, $userdata);
349
                } elseif ($type == 'delivery') {
350
                    $noAccountUser['delivery'] = array_merge($noAccountUser['delivery'], $userdata);
351
                }
352
353
                session()->put('noAccountUser', $noAccountUser);
354
            }
355
        } else {
356
            $user = auth('web')->user();
357
358
            if ($type == 'bill') {
359
                $id = $user->clientBillAddress->id;
0 ignored issues
show
Bug introduced by
Accessing clientBillAddress on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
360
361
                if ($user->clientDeliveryAddress->id == $user->clientBillAddress->id) {
0 ignored issues
show
Bug introduced by
Accessing clientDeliveryAddress on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
362
                    $clientAddress = $this->clientAddress->createByClient($userdata, $user->id);
0 ignored issues
show
Bug introduced by
Accessing 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 clientAddress does not exist on App\Http\Controllers\Frontend\CheckoutController. Did you maybe forget to declare it?
Loading history...
363
                    ClientService::setBillOrDeliveryAddress(config()->get('app.shop_id'), $user->id, $clientAddress->id, $type);
364
                } else {
365
                    $clientAddress = ClientService::editAddress($user->id, $id, $userdata);
0 ignored issues
show
Unused Code introduced by
The assignment to $clientAddress is dead and can be removed.
Loading history...
366
                }
367
            } elseif ($type == 'delivery') {
368
                $id = $user->clientDeliveryAddress->id;
369
370
                if ($user->clientDeliveryAddress->id == $user->clientBillAddress->id) {
371
                    $clientAddress = $this->clientAddress->createByClient($userdata, $user->id);
372
                    ClientService::setBillOrDeliveryAddress(config()->get('app.shop_id'), $user->id, $clientAddress->id, $type);
373
                } else {
374
                    $clientAddress = ClientService::editAddress($user->id, $id, $userdata);
375
                }
376
            }
377
        }
378
379
        return redirect()->to('cart/checkout');        
380
    }
381
}