Passed
Push — master ( cb5f39...062e0c )
by Matthijs
06:26
created

CheckoutController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
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
    public function checkout()
17
    {
18
        $sendingMethodsList = SendingMethodService::selectAllActiveByShopId(config()->get('app.shop_id'));
19
20
        if (Cart::getContent()->count()) {
21
22
            $paymentMethodsList = Cart::getConditionsByType('sending_method')->first()->getAttributes()['data']['related_payment_methods_list'];
23
         
24
            if(!Cart::getConditionsByType('sending_method')->count()) {
25
                Notification::error('Selecteer een verzendwijze');
26
                return redirect()->to('cart');
27
            }
28
29
            if(!Cart::getConditionsByType('payment_method')->count()) {
30
31
                Notification::error('Selecteer een betaalwijze');
32
                return redirect()->to('cart');
33
            }
34
35
        } else {
36
            return redirect()->to('cart');
37
        }
38
39
40
41
        if (auth('web')->guest()) {
42
            $noAccountUser = session()->get('noAccountUser');
43
            if ($noAccountUser) {
44
                if (!isset($noAccountUser['delivery'])) {
45
                    $noAccountUser['delivery'] = $noAccountUser;
46
                    session()->put('noAccountUser', $noAccountUser);
47
                }
48
  
49
                return view('frontend.checkout.no-account')->with(array( 
50
                    'noAccountUser' =>  $noAccountUser, 
51
                    'sendingMethodsList' => $sendingMethodsList, 
52
                    'paymentMethodsList' => $paymentMethodsList));
53
            }
54
              
55
             return view('frontend.checkout.login')->with(array(  'sendingMethodsList' => $sendingMethodsList, 'paymentMethodsList' => $paymentMethodsList));
56
        }
57
58
        $user = auth('web')->user();
59
        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

59
        self::/** @scrutinizer ignore-call */ 
60
              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...
60
61
        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

61
        if (!$user->/** @scrutinizer ignore-call */ clientDeliveryAddress()->count()) {
Loading history...
62
            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
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 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...
63
            return redirect()->to('cart/checkout');
64
        }
65
66
        return view('frontend.checkout.index')->with(array(
67
            'user' =>  $user, 
68
            'sendingMethodsList' => $sendingMethodsList, 
69
            'paymentMethodsList' => $paymentMethodsList));
70
    }
71
72
73
    public function postCheckoutLogin(Request $request)
74
    {
75
        // create the validation rules ------------------------
76
        $rules = array(
77
            'email'         => 'required|email',     // required and must be unique in the ducks table
78
            'password'      => 'required'
79
        );
80
81
        $validator = Validator::make($request->all(), $rules);
82
83
        if ($validator->fails()) {
84
85
            foreach ($validator->errors()->all() as $error) {
86
                Notification::error($error);
87
            }
88
89
            return redirect()->to('cart/checkout')
90
            ->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

90
            ->withErrors(/** @scrutinizer ignore-type */ true, 'login')->withInput();
Loading history...
91
        }
92
93
        $userdata = array(
94
            'email' => $request->get('email'),
95
            'password' => $request->get('password'),
96
            'confirmed' => 1,
97
            'active' => 1,
98
            'shop_id' => config()->get('app.shop_id')
99
        );
100
101
        /* Try to authenticate the credentials */
102
        if (auth('web')->attempt($userdata)) {
103
            // we are now logged in, go to admin
104
            return redirect()->to('cart/checkout');
105
        }
106
107
        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

107
        Notification::error(/** @scrutinizer ignore-type */ trans('message.error.data-is-incorrect'));
Loading history...
108
        return redirect()->to('cart/checkout')->withErrors(true, 'login')->withInput(); 
109
    }
110
111
    //to-do: transfer logic to repo
112
    public function postCheckoutRegister(Request $request)
113
    {
114
        if (!Cart::getContent()->count()) {  
115
            return redirect()->to('cart/checkout');
116
        }
117
118
        $userdata = $request->all();
119
120
        $rules = array(
121
            'email'         => 'required|email',     // required and must be unique in the ducks table
122
            'password'      => 'required',
123
            'firstname'     => 'required',
124
            'lastname'      => 'required',
125
            'zipcode'       => 'required',
126
            'housenumber'   => 'required|numeric',
127
            'street'        => 'required',
128
            'city'          => 'required'
129
            );
130
131
        if (!$userdata['password']) {
132
            unset($rules['email']);
133
            unset($rules['password']);
134
        } 
135
136
        $validator = Validator::make($request->all(), $rules);
137
138
        if ($validator->fails()) {
139
            // get the error messages from the validator
140
            foreach ($validator->errors()->all() as $error) {
141
                Notification::error($error);
142
            }
143
            // redirect our user back to the form with the errors from the validator
144
            return redirect()->to('cart/checkout')
145
            ->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

145
            ->withErrors(/** @scrutinizer ignore-type */ true, 'register')->withInput();
Loading history...
146
        }
147
148
        if ($userdata['password']) {
149
            $registerAttempt = ClientService::validateRegister($userdata, config()->get('app.shop_id'));
150
151
            if ($registerAttempt) {
152
                $register = ClientService::register($userdata, config()->get('app.shop_id'), true);
153
            } else {
154
                $client = ClientService::findByEmail($userdata['email'], config()->get('app.shop_id'));
155
156
                if ($client->account_created) {
157
                    Notification::error('Je hebt al een account. Login aan de linkerkant of vraag een nieuw wachtwoord aan.');
158
                    return redirect()->to('cart/checkout')->withInput()->withErrors('Dit emailadres is al in gebruik. Je kan links inloggen.', 'register');
159
                } else {
160
                    $register = ClientService::createAccount($userdata, config()->get('app.shop_id'));
161
                }
162
            }
163
164
            if ($register) {
165
                $data = $register;
166
                $data['shop'] = app('shop');
167
        
168
                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...
169
            
170
                    $message->to($data['email'])->from($data['shop']->email, $data['shop']->title)->subject('Je bent geregistreerd.');
171
                });
172
173
                $userdata = array(
174
                    'email' => $request->get('email'),
175
                    'password' => $request->get('password'),
176
                    'confirmed' => 1,
177
                    'active' => 1
178
                );
179
180
                auth('web')->attempt($userdata);
181
182
                return redirect()->to('cart/checkout')->withErrors('Je bent geregistreerd. Er is een bevestigingsmail gestuurd.', 'login');
183
            } else {
184
                Notification::error('Je hebt al een account');
185
                return redirect()->to('cart/checkout')->withErrors(true, 'register')->withInput();
186
            }
187
        }
188
        
189
        unset($userdata['password']);
190
        $registerAttempt = ClientService::validateRegisterNoAccount($userdata, config()->get('app.shop_id'));
191
192
        if ($registerAttempt) {
193
            $register = ClientService::register($userdata, config()->get('app.shop_id'));   
194
            $userdata['client_id'] = $register->id;
195
        } else {
196
            $client = ClientService::findByEmail($userdata['email'], config()->get('app.shop_id'));
197
            if ($client) {
198
                $userdata['client_id'] = $client->id;
199
            }
200
        }
201
202
        session()->put('noAccountUser', $userdata);
203
        return redirect()->to('cart/checkout');
204
       
205
        
206
    }
207
208
    public function postComplete(Request $request)
209
    {
210
        $noAccountUser = session()->get('noAccountUser');
211
        if (auth('web')->guest() and !$noAccountUser) {
212
            return view('frontend.checkout.login');
213
        }
214
215
        if (!Cart::getContent()->count()) {        
216
            return redirect()->to('cart/checkout');
217
        }
218
219
        $data = array(
220
            'products' => Cart::getContent()->toArray(),
221
            'price_with_tax' => Cart::getTotalWithTax(false),
222
            'price_without_tax' => Cart::getTotalWithoutTax(false),
223
            'comments' => $request->get('comments'),
224
            'browser_detect' => serialize(BrowserDetect::toArray())
225
        );
226
227
228
        if (auth('web')->check()) {
229
            $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...
230
        } else {
231
            $data['user_id'] = $noAccountUser['client_id'];
232
        }     
233
234
        if(Cart::getConditionsByType('sending_method')->count()) {
235
            $data['sending_method'] = Cart::getConditionsByType('sending_method');
236
        }
237
238
        if(Cart::getConditionsByType('sending_method_country_price')->count()) {
239
            $data['sending_method_country_price'] = Cart::getConditionsByType('sending_method_country_price');
240
        }
241
242
        if(Cart::getConditionsByType('payment_method')->count()) {
243
            $data['payment_method'] = Cart::getConditionsByType('payment_method');
244
        }
245
246
        $orderInsertAttempt = OrderService::createByUserAndShopId($data, config()->get('app.shop_id'), $noAccountUser);
247
248
        if ($orderInsertAttempt AND $orderInsertAttempt->count()) {
249
            if ($orderInsertAttempt->OrderPaymentMethod and $orderInsertAttempt->OrderPaymentMethod->paymentMethod->order_confirmed_order_status_id) {
250
                $orderStatus = OrderService::updateStatus($orderInsertAttempt->id, $orderInsertAttempt->OrderPaymentMethod->paymentMethod->order_confirmed_order_status_id);
251
                if ($orderInsertAttempt->OrderPaymentMethod->paymentMethod->order_confirmed_order_status_id) {
252
                    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...
253
                }
254
            }
255
256
            session()->put('orderData', $orderInsertAttempt);
257
258
            if ($orderInsertAttempt->OrderPaymentMethod and $orderInsertAttempt->OrderPaymentMethod->paymentMethod->payment_external) {
259
                return redirect()->to('cart/payment');
260
            }
261
262
            app('cart')->clear();
263
            app('cart')->clearCartConditions();  
264
            session()->flush('noAccountUser');
265
            $body = "";
266
            return view('frontend.checkout.complete')->with(array('body' => $body));            
267
        }
268
269
        return redirect()->to('cart/checkout');
270
    }
271
272
    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

272
    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...
273
274
        if (!Cart::getContent()->count()) {        
275
            return redirect()->to('cart/checkout');
276
        }              
277
278
        if (auth('web')->guest()) {
279
            $noAccountUser = session()->get('noAccountUser');
280
            if ($noAccountUser) {
281
                
282
                $address = $noAccountUser;
283
                if ($type == 'delivery') {
284
                    $address = $noAccountUser['delivery'];
285
                }
286
287
                return view('frontend.checkout.edit-address-no-account')->with(array('type' => $type, 'noAccountUser' =>  $noAccountUser, 'clientAddress' => $address));
288
            }
289
        }
290
291
        $user = auth('web')->user();
292
293
        if ($type == 'delivery') {
294
            $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...
295
        } else {
296
            $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...
297
        }
298
299
        return view('frontend.checkout.edit-address')->with(array('type' => $type, 'user' => $user, 'clientAddress' => $address));
300
    }
301
302
    public function postEditAddress(Request $request, $type)
303
    {
304
        if (!Cart::getContent()->count()) {        
305
            return redirect()->to('cart/checkout');
306
        } 
307
        
308
        $userdata = $request->all();
309
310
        // create the validation rules ------------------------
311
        $rules = array(
312
            'firstname'     => 'required',
313
            'lastname'      => 'required',
314
            'zipcode'       => 'required',
315
            'housenumber'   => 'required|numeric',
316
            'street'        => 'required',
317
            'city'          => 'required'
318
        );
319
320
        $validator = Validator::make($request->all(), $rules);
321
322
        if ($validator->fails()) {
323
            // get the error messages from the validator
324
            foreach ($validator->errors()->all() as $error) {
325
                Notification::error($error);
326
            }
327
328
            // redirect our user back to the form with the errors from the validator
329
            return redirect()->to('cart/edit-address/'.$type)
330
            ->with(array('type' => $type))->withInput();
331
        }
332
333
        if (auth('web')->guest()) {
334
            $noAccountUser = session()->get('noAccountUser');
335
            if ($noAccountUser) {
336
                if ($type == 'bill') {
337
                    $noAccountUser = array_merge($noAccountUser, $userdata);
338
                } elseif ($type == 'delivery') {
339
                    $noAccountUser['delivery'] = array_merge($noAccountUser['delivery'], $userdata);
340
                }
341
342
                session()->put('noAccountUser', $noAccountUser);
343
            }
344
        } else {
345
            $user = auth('web')->user();
346
347
            if ($type == 'bill') {
348
                $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...
349
350
                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...
351
                    $clientAddress = $this->clientAddress->createByClient($userdata, $user->id);
0 ignored issues
show
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...
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...
352
                    ClientService::setBillOrDeliveryAddress(config()->get('app.shop_id'), $user->id, $clientAddress->id, $type);
353
                } else {
354
                    $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...
355
                }
356
            } elseif ($type == 'delivery') {
357
                $id = $user->clientDeliveryAddress->id;
358
359
                if ($user->clientDeliveryAddress->id == $user->clientBillAddress->id) {
360
                    $clientAddress = $this->clientAddress->createByClient($userdata, $user->id);
361
                    ClientService::setBillOrDeliveryAddress(config()->get('app.shop_id'), $user->id, $clientAddress->id, $type);
362
                } else {
363
                    $clientAddress = ClientService::editAddress($user->id, $id, $userdata);
364
                }
365
            }
366
        }
367
368
        return redirect()->to('cart/checkout');        
369
    }
370
}