Completed
Push — master ( 81ffa0...2d214f )
by vijay
107:48 queued 56:59
created

CheckoutController::postCheckout()   B

Complexity

Conditions 7
Paths 60

Size

Total Lines 52
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 3 Features 0
Metric Value
cc 7
eloc 31
c 7
b 3
f 0
nc 60
nop 1
dl 0
loc 52
rs 7.2396

How to fix   Long Method   

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
2
3
namespace App\Http\Controllers\Front;
4
5
use App\Http\Controllers\Common\MailChimpController;
6
use App\Http\Controllers\Common\TemplateController;
7
use App\Http\Controllers\Controller;
8
use App\Model\Common\Setting;
9
use App\Model\Common\Template;
10
use App\Model\Order\Invoice;
11
use App\Model\Order\InvoiceItem;
12
use App\Model\Order\Order;
13
use App\Model\Payment\Plan;
14
use App\Model\Product\Price;
15
use App\Model\Product\Product;
16
use App\Model\Product\Subscription;
17
use App\User;
18
use Cart;
19
use Illuminate\Http\Request;
20
21
class CheckoutController extends Controller
22
{
23
    public $subscription;
24
    public $plan;
25
    public $templateController;
26
    public $product;
27
    public $price;
28
    public $user;
29
    public $setting;
30
    public $template;
31
    public $order;
32
    public $addon;
33
    public $invoice;
34
    public $invoiceItem;
35
    public $mailchimp;
36
37
    public function __construct()
38
    {
39
        $subscription = new Subscription();
40
        $this->subscription = $subscription;
41
42
        $plan = new Plan();
43
        $this->plan = $plan;
44
45
        $templateController = new TemplateController();
46
        $this->templateController = $templateController;
47
48
        $product = new Product();
49
        $this->product = $product;
50
51
        $price = new Price();
52
        $this->price = $price;
53
54
        $user = new User();
55
        $this->user = $user;
56
57
        $setting = new Setting();
58
        $this->setting = $setting;
59
60
        $template = new Template();
61
        $this->template = $template;
62
63
        $order = new Order();
64
        $this->order = $order;
65
66
        $invoice = new Invoice();
67
        $this->invoice = $invoice;
68
69
        $invoiceItem = new InvoiceItem();
70
        $this->invoiceItem = $invoiceItem;
71
72
        $mailchimp = new MailChimpController();
73
        $this->mailchimp = $mailchimp;
74
    }
75
76
    public function CheckoutForm(Request $request)
77
    {
78
        if (!\Auth::user()) {
79
            $url = $request->segments();
80
81
            \Session::put('session-url', $url[0]);
82
83
            return redirect('auth/login')->with('fails', 'Please login');
84
        }
85
        $content = Cart::getContent();
86
        $require = [];
87
        foreach ($content as $key => $item) {
88
            $attributes[] = $item->attributes;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$attributes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $attributes = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
89
            $require_domain = $this->product->where('id', $item->id)->first()->require_domain;
90
            if ($require_domain == 1) {
91
                $require[$key] = $item->id;
92
            }
93
        }
94
        if (count($require) > 0) {
95
            $this->validate($request, [
96
                'domain.*' => 'required|url',
97
                    ], [
98
                'domain.*.required' => 'Please provide Domain name',
99
                'domain.*.url'      => 'Domain name is not valid',
100
            ]);
101
        }
102
        try {
103
            $domain = $request->input('domain');
104
            if (count($domain) > 0) {
105
                foreach ($domain as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $domain of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
106
                    \Session::put('domain'.$key, $value);
107
                }
108
            }
109
110
            return view('themes.default1.front.checkout', compact('content', 'attributes'));
111
        } catch (\Exception $ex) {
112
            return redirect()->back()->with('fails', $ex->getMessage());
113
        }
114
    }
115
116
    public function postCheckout(Request $request)
117
    {
118
        if (\Cart::getSubTotal() > 0) {
119
            $v = $this->validate($request, [
0 ignored issues
show
Unused Code introduced by
$v 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...
Bug introduced by
Are you sure the assignment to $v is correct as $this->validate($request...se a payment gateway')) (which targets Illuminate\Foundation\Va...tesRequests::validate()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
120
                'payment_gateway' => 'required',
121
                    ], [
122
123
                'payment_gateway.required' => 'Please choose a payment gateway',
124
            ]);
125
        }
126
        try {
127
            if (!$this->setting->where('id', 1)->first()) {
128
                return redirect()->back()->with('fails', 'Complete your settings');
129
            }
130
            /*
131
             * Do order, invoicing etc
132
             */
133
            $invoice_controller = new \App\Http\Controllers\Order\InvoiceController();
134
            $invoice = $invoice_controller->GenerateInvoice();
135
            $payment_method = $request->input('payment_gateway');
136
            $status = 'pending';
0 ignored issues
show
Unused Code introduced by
$status 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...
137
            if (!$payment_method) {
138
                $payment_method = 'free';
0 ignored issues
show
Unused Code introduced by
$payment_method 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...
139
                $status = 'success';
0 ignored issues
show
Unused Code introduced by
$status 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...
140
            }
141
            $invoiceid = $invoice->id;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Model\Order\Invoice>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
142
            $amount = $invoice->grand_total;
0 ignored issues
show
Documentation introduced by
The property grand_total does not exist on object<App\Model\Order\Invoice>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Unused Code introduced by
$amount 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...
143
144
            //dd($payment);
145
            $url = '';
0 ignored issues
show
Unused Code introduced by
$url 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...
146
            //trasfer the control to event if cart price is not equal 0
147
            if (Cart::getSubTotal() != 0) {
148
149
                //$invoice_controller->doPayment($payment_method, $invoiceid, $amount,'','',$status);
150
                \Event::fire(new \App\Events\PaymentGateway(['request' => $request, 'cart' => Cart::getContent(), 'order' => $invoice]));
151
            } else {
152
                $this->checkoutAction($invoice);
153
                $check_product_category = $this->product($invoiceid);
154
                $url = '';
155
                if ($check_product_category->category == 'product') {
156
                    $url = 'You can also download the product <a href='.url('download/'.\Auth::user()->id."/$invoice->number").'>here</a>';
157
                }
158
                \Cart::clear();
159
160
                return redirect()->back()->with('success', \Lang::get('message.check-your-mail-for-further-datails').$url);
161
            }
162
        } catch (\Exception $ex) {
163
            dd($ex);
164
165
            return redirect()->back()->with('fails', $ex->getMessage());
166
        }
167
    }
168
169
    public function checkoutAction($invoice)
170
    {
171
        try {
172
173
            //get elements from invoice
174
            $invoice_number = $invoice->number;
175
            $invoice_id = $invoice->id;
176
            $invoice->status = 'success';
177
            $invoice->save();
178
            //dd($invoice->id);
179
180
            $invoice_items = $this->invoiceItem->where('invoice_id', $invoice->id)->first();
181
            $product = $invoice_items->product_name;
182
183
            $user_id = \Auth::user()->id;
184
185
            $url = '';
186
            $check_product_category = $this->product($invoice_id);
187
            if ($check_product_category->category == 'product') {
188
                $url = url("download/$user_id/$invoice_number");
189
                //execute the order
190
                $order = new \App\Http\Controllers\Order\OrderController();
191
                $order->executeOrder($invoice->id, $order_status = 'executed');
192
            }
193
            //get system values
194
            $settings = new Setting();
195
            $settings = $settings->findOrFail(1);
196
            $name = \Auth::user()->first_name.' '.\Auth::user()->last_name;
197
            $from = $settings->email;
198
            $to = \Auth::user()->email;
199
            $data = $this->template->where('type', 7)->first()->data;
200
            $subject = $this->template->where('type', 7)->first()->name;
201
            $replace = ['url' => $url, 'name' => $name, 'product' => $product];
202
203
            //send mail
204
            $template_controller = new TemplateController();
205
            $template_controller->Mailing($from, $to, $data, $subject, $replace);
206
        } catch (\Exception $ex) {
207
            //dd($ex);
208
209
            return redirect()->back()->with('fails', $ex->getMessage());
210
        }
211
    }
212
213
    public function product($invoiceid)
214
    {
215
        try {
216
            $invoice = $this->invoiceItem->where('invoice_id', $invoiceid)->first();
217
            $name = $invoice->product_name;
218
            $product = $this->product->where('name', $name)->first();
219
220
            return $product;
221
        } catch (\Exception $ex) {
222
            dd($ex);
223
            throw new \Exception($ex->getMessage());
224
        }
225
    }
226
227
//    public function GenerateOrder() {
228
//        try {
229
//
230
//            $products = [];
231
//            $items = \Cart::getContent();
232
//            foreach ($items as $item) {
233
//
234
//                //this is product
235
//                $id = $item->id;
236
//                $this->AddProductToOrder($id);
237
//            }
238
//        } catch (\Exception $ex) {
239
//            dd($ex);
240
//            throw new \Exception('Can not Generate Order');
241
//        }
242
//    }
243
//
244
//    public function AddProductToOrder($id) {
245
//        try {
246
//            $cart = \Cart::get($id);
247
//            $client = \Auth::user()->id;
248
//            $payment_method = \Input::get('payment_gateway');
249
//            $promotion_code = '';
250
//            $order_status = 'pending';
251
//            $serial_key = '';
252
//            $product = $id;
253
//            $addon = '';
254
//            $domain = '';
255
//            $price_override = $cart->getPriceSumWithConditions();
256
//            $qty = $cart->quantity;
257
//
258
//            $planid = $this->price->where('product_id', $id)->first()->subscription;
259
//
260
//            $or = $this->order->create(['client' => $client, 'payment_method' => $payment_method, 'promotion_code' => $promotion_code, 'order_status' => $order_status, 'serial_key' => $serial_key, 'product' => $product, 'addon' => $addon, 'domain' => $domain, 'price_override' => $price_override, 'qty' => $qty]);
261
//
262
//            $this->AddSubscription($or->id, $planid);
263
//        } catch (\Exception $ex) {
264
//            dd($ex);
265
//            throw new \Exception('Can not Generate Order for Product');
266
//        }
267
//    }
268
//
269
//    public function AddSubscription($orderid, $planid) {
270
//        try {
271
//            $days = $this->plan->where('id', $planid)->first()->days;
272
//            //dd($days);
273
//            if ($days > 0) {
274
//                $dt = \Carbon\Carbon::now();
275
//                //dd($dt);
276
//                $user_id = \Auth::user()->id;
277
//                $ends_at = $dt->addDays($days);
278
//            } else {
279
//                $ends_at = '';
280
//            }
281
//            $this->subscription->create(['user_id' => \Auth::user()->id, 'plan_id' => $planid, 'order_id' => $orderid, 'ends_at' => $ends_at]);
282
//        } catch (\Exception $ex) {
283
//            dd($ex);
284
//            throw new \Exception('Can not Generate Subscription');
285
//        }
286
//    }
287
//
288
//    public function GenerateInvoice() {
289
//        try {
290
//
291
//            $user_id = \Auth::user()->id;
292
//            $number = rand(11111111, 99999999);
293
//            $date = \Carbon\Carbon::now();
294
//            $grand_total = \Cart::getSubTotal();
295
//
296
//            $invoice = $this->invoice->create(['user_id' => $user_id, 'number' => $number, 'date' => $date, 'grand_total' => $grand_total]);
297
//            foreach (\Cart::getContent() as $cart) {
298
//                $this->CreateInvoiceItems($invoice->id, $cart);
299
//            }
300
//        } catch (\Exception $ex) {
301
//            dd($ex);
302
//            throw new \Exception('Can not Generate Invoice');
303
//        }
304
//    }
305
//
306
//    public function CreateInvoiceItems($invoiceid, $cart) {
307
//        try {
308
//
309
//            $product_name = $cart->name;
310
//            $regular_price = $cart->price;
311
//            $quantity = $cart->quantity;
312
//            $subtotal = $cart->getPriceSumWithConditions();
313
//
314
//            $tax_name = '';
315
//            $tax_percentage = '';
316
//
317
//            foreach ($cart->attributes['tax'] as $tax) {
318
//                //dd($tax['name']);
319
//                $tax_name .= $tax['name'] . ',';
320
//                $tax_percentage .= $tax['rate'] . ',';
321
//            }
322
//
323
//            //dd($tax_name);
324
//
325
//            $invoiceItem = $this->invoiceItem->create(['invoice_id' => $invoiceid, 'product_name' => $product_name, 'regular_price' => $regular_price, 'quantity' => $quantity, 'tax_name' => $tax_name, 'tax_percentage' => $tax_percentage, 'subtotal' => $subtotal]);
326
//        } catch (\Exception $ex) {
327
//            dd($ex);
328
//            throw new \Exception('Can not create Invoice Items');
329
//        }
330
//    }
331
}
332