Completed
Push — master ( 448de3...10316f )
by Luke
02:17
created

LaraCart::taxTotal()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 1 Features 0
Metric Value
c 8
b 1
f 0
dl 0
loc 30
rs 6.7272
cc 7
eloc 17
nc 7
nop 1
1
<?php
2
3
namespace LukePOLO\LaraCart;
4
5
use Illuminate\Contracts\Events\Dispatcher;
6
use Illuminate\Session\SessionManager;
7
use LukePOLO\LaraCart\Contracts\CouponContract;
8
use LukePOLO\LaraCart\Contracts\LaraCartContract;
9
10
/**
11
 * Class LaraCart
12
 *
13
 * @package LukePOLO\LaraCart
14
 */
15
class LaraCart implements LaraCartContract
16
{
17
    const QTY = 'qty';
18
    const HASH = 'generateCartHash';
19
    const PRICE = 'price';
20
    const SERVICE = 'laracart';
21
    const RANHASH = 'generateRandomCartItemHash';
22
23
    protected $events;
24
    protected $session;
25
26
    public $cart;
27
28
    /**
29
     * LaraCart constructor.
30
     *
31
     * @param SessionManager $session
32
     * @param Dispatcher $events
33
     */
34
    public function __construct(SessionManager $session, Dispatcher $events)
35
    {
36
        $this->session = $session;
37
        $this->events = $events;
38
39
        $this->setInstance($this->session->get('laracart.instance', 'default'));
40
    }
41
42
    /**
43
     * Sets and Gets the instance of the cart in the session we should be using
44
     *
45
     * @param string $instance
46
     *
47
     * @return LaraCart
48
     */
49
    public function setInstance($instance = 'default')
50
    {
51
        $this->get($instance);
52
53
        $this->session->set('laracart.instance', $instance);
54
55
        $this->events->fire('laracart.new');
56
57
        return $this;
58
    }
59
60
    /**
61
     * Gets the instance in the session
62
     *
63
     * @param string $instance
64
     *
65
     * @return $this cart instance
66
     */
67
    public function get($instance = 'default')
68
    {
69
        if (empty($this->cart = $this->session->get(config('laracart.cache_prefix', 'laracart') . '.' . $instance))) {
70
            $this->cart = new Cart($instance);
71
        }
72
73
        return $this;
74
    }
75
76
    /**
77
     * Gets an an attribute from the cart
78
     *
79
     * @param $attribute
80
     * @param $defaultValue
81
     *
82
     * @return mixed
83
     */
84
    public function getAttribute($attribute, $defaultValue = null)
85
    {
86
        return array_get($this->cart->attributes, $attribute, $defaultValue);
87
    }
88
89
    /**
90
     * Gets all the carts attributes
91
     *
92
     * @return mixed
93
     */
94
    public function getAttributes()
95
    {
96
        return $this->cart->attributes;
97
    }
98
99
    /**
100
     * Adds an Attribute to the cart
101
     *
102
     * @param $attribute
103
     * @param $value
104
     */
105
    public function setAttribute($attribute, $value)
106
    {
107
        array_set($this->cart->attributes, $attribute, $value);
108
109
        $this->update();
110
    }
111
112
    /**
113
     * Updates cart session
114
     */
115
    public function update()
116
    {
117
        $this->session->set(config('laracart.cache_prefix', 'laracart') . '.' . $this->cart->instance, $this->cart);
118
119
        $this->events->fire('laracart.update', $this->cart);
120
    }
121
122
    /**
123
     * Removes an attribute from the cart
124
     *
125
     * @param $attribute
126
     */
127
    public function removeAttribute($attribute)
128
    {
129
        array_forget($this->cart->attributes, $attribute);
130
131
        $this->update();
132
    }
133
134
    /**
135
     * Creates a CartItem and then adds it to cart
136
     *
137
     * @param string|int $itemID
138
     * @param null $name
139
     * @param int $qty
140
     * @param string $price
141
     * @param array $options
142
     * @param bool|true $taxable
143
     *
144
     * @return CartItem
145
     */
146
    public function addLine($itemID, $name = null, $qty = 1, $price = '0.00', $options = [], $taxable = true)
147
    {
148
        return $this->add($itemID, $name, $qty, $price, $options, $taxable, true);
149
    }
150
151
    /**
152
     * Creates a CartItem and then adds it to cart
153
     *
154
     * @param $itemID
155
     * @param null $name
156
     * @param int $qty
157
     * @param string $price
158
     * @param array $options
159
     * @param bool|false $taxable
160
     * @param bool|false $lineItem
161
     *
162
     * @return CartItem
163
     */
164
    public function add(
165
        $itemID,
166
        $name = null,
167
        $qty = 1,
168
        $price = '0.00',
169
        $options = [],
170
        $taxable = true,
171
        $lineItem = false
172
    ) {
173
        $item = $this->addItem(
174
            new CartItem(
175
                $itemID,
176
                $name,
177
                $qty,
178
                $price,
179
                $options,
180
                $taxable,
181
                $lineItem
182
            )
183
        );
184
185
        return $this->getItem($item->getHash());
186
    }
187
188
    /**
189
     * Adds the cartItem into the cart session
190
     *
191
     * @param CartItem $cartItem
192
     *
193
     * @return CartItem
194
     */
195
    public function addItem(CartItem $cartItem)
196
    {
197
        $itemHash = $cartItem->generateHash();
198
199
        if ($this->getItem($itemHash)) {
200
            $this->getItem($itemHash)->qty += $cartItem->qty;
0 ignored issues
show
Documentation introduced by
The property qty does not exist on object<LukePOLO\LaraCart\CartItem>. 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...
201
        } else {
202
            $this->cart->items[] = $cartItem;
203
        }
204
205
        $this->events->fire('laracart.addItem', $cartItem);
206
207
        $this->update();
208
209
        return $cartItem;
210
    }
211
212
    /*
213
     * Find items in the cart matching a data set
214
     *
215
     * @return array
216
     */
217
    public function find($data)
218
    {
219
        $matches = [];
220
221
        foreach ($this->getItems() as $item) {
222
            if ($item->find($data)) {
223
                $matches[] = $item;
224
            }
225
        }
226
227
        return $matches;
228
    }
229
230
    /**
231
     * Finds a cartItem based on the itemHash
232
     *
233
     * @param $itemHash
234
     *
235
     * @return CartItem | null
236
     */
237
    public function getItem($itemHash)
238
    {
239
        return array_get($this->getItems(), $itemHash);
240
    }
241
242
    /**
243
     * Gets all the items within the cart
244
     *
245
     * @return array
246
     */
247
    public function getItems()
248
    {
249
        $items = [];
250
        if (isset($this->cart->items) === true) {
251
            foreach ($this->cart->items as $item) {
252
                $items[$item->getHash()] = $item;
253
            }
254
        }
255
256
        return $items;
257
    }
258
259
    /**
260
     * Updates an items attributes
261
     *
262
     * @param $itemHash
263
     * @param $key
264
     * @param $value
265
     *
266
     * @return CartItem
267
     *
268
     * @throws Exceptions\InvalidPrice
269
     * @throws Exceptions\InvalidQuantity
270
     */
271
    public function updateItem($itemHash, $key, $value)
272
    {
273
        if (empty($item = $this->getItem($itemHash)) === false) {
274
            $item->$key = $value;
275
        }
276
277
        $item->generateHash();
278
279
        return $item;
280
    }
281
282
    /**
283
     * Removes a CartItem based on the itemHash
284
     *
285
     * @param $itemHash
286
     */
287
    public function removeItem($itemHash)
288
    {
289
        foreach ($this->cart->items as $itemKey => $item) {
290
            if ($item->getHash() == $itemHash) {
291
                unset($this->cart->items[$itemKey]);
292
                break;
293
            }
294
        }
295
296
        $this->events->fire('laracart.removeItem', $itemHash);
297
    }
298
299
    /**
300
     * Empties the carts items
301
     */
302
    public function emptyCart()
303
    {
304
        unset($this->cart->items);
305
306
        $this->update();
307
308
        $this->events->fire('laracart.empty', $this->cart->instance);
309
    }
310
311
    /**
312
     * Completely destroys cart and anything associated with it
313
     */
314
    public function destroyCart()
315
    {
316
        $instance = $this->cart->instance;
317
318
        $this->session->forget(config('laracart.cache_prefix', 'laracart') . '.' . $instance);
319
320
        $this->setInstance('default');
321
322
        $this->events->fire('laracart.destroy', $instance);
323
    }
324
325
    /**
326
     * Gets the coupons for the current cart
327
     *
328
     * @return array
329
     */
330
    public function getCoupons()
331
    {
332
        return $this->cart->coupons;
333
    }
334
335
    /**
336
     * Finds a specific coupon in the cart
337
     *
338
     * @param $code
339
     * @return mixed
340
     */
341
    public function findCoupon($code)
342
    {
343
        return array_get($this->cart->coupons, $code);
344
    }
345
346
    /**
347
     * Applies a coupon to the cart
348
     *
349
     * @param CouponContract $coupon
350
     */
351
    public function addCoupon(CouponContract $coupon)
352
    {
353
        if (!$this->cart->multipleCoupons) {
354
            $this->cart->coupons = [];
355
        }
356
357
        $this->cart->coupons[$coupon->code] = $coupon;
0 ignored issues
show
Bug introduced by
Accessing code on the interface LukePOLO\LaraCart\Contracts\CouponContract suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
358
359
        $this->update();
360
    }
361
362
    /**
363
     * Removes a coupon in the cart
364
     *
365
     * @param $code
366
     */
367
    public function removeCoupon($code)
368
    {
369
        foreach ($this->getItems() as $item) {
370
            if (isset($item->code) && $item->code == $code) {
371
                $item->code = null;
372
                $item->discount = null;
373
                $item->couponInfo = [];
374
            }
375
        }
376
377
        array_forget($this->cart->coupons, $code);
378
379
        $this->update();
380
    }
381
382
    /**
383
     * Gets a speific fee from the fees array
384
     *
385
     * @param $name
386
     *
387
     * @return mixed
388
     */
389
    public function getFee($name)
390
    {
391
        return array_get($this->cart->fees, $name, new CartFee(null, false));
392
    }
393
394
    /**
395
     * Allows to charge for additional fees that may or may not be taxable
396
     * ex - service fee , delivery fee, tips
397
     *
398
     * @param $name
399
     * @param $amount
400
     * @param bool|false $taxable
401
     * @param array $options
402
     */
403
    public function addFee($name, $amount, $taxable = false, Array $options = [])
404
    {
405
        array_set($this->cart->fees, $name, new CartFee($amount, $taxable, $options));
406
407
        $this->update();
408
    }
409
410
    /**
411
     * Reemoves a fee from the fee array
412
     *
413
     * @param $name
414
     */
415
    public function removeFee($name)
416
    {
417
        array_forget($this->cart->fees, $name);
418
419
        $this->update();
420
    }
421
422
    /**
423
     * Gets the total tax for the cart
424
     *
425
     * @param bool|true $format
426
     *
427
     * @return string
428
     */
429
    public function taxTotal($format = true)
430
    {
431
        $totalTax = 0;
432
        $discounted = 0;
433
        $totalDiscount = $this->totalDiscount(false);
434
435
        if ($this->count() != 0) {
436
            foreach ($this->getItems() as $item) {
437
                if ($discounted >= $totalDiscount) {
438
                    $totalTax += $item->tax();
439
                } else {
440
                    $itemPrice = $item->subTotal(false);
441
442
                    if (($discounted + $itemPrice) > $totalDiscount) {
443
                        $totalTax += $item->tax($totalDiscount - $discounted);
444
                    }
445
446
                    $discounted += $itemPrice;
447
                }
448
            }
449
        }
450
451
        foreach ($this->getFees() as $fee) {
452
            if ($fee->taxable) {
453
                $totalTax += $fee->amount * $this->cart->tax;
454
            }
455
        }
456
457
        return $this->formatMoney($totalTax, null, null, $format);
458
    }
459
460
    /**
461
     * Gets the total of the cart with or without tax
462
     *
463
     * @param boolean $format
464
     * @param boolean $withDiscount
465
     *
466
     * @return string
467
     */
468
    public function total($format = true, $withDiscount = true)
469
    {
470
        $total = $this->subTotal(false) + $this->feeTotals(false);
471
472
        if ($withDiscount) {
473
            $total -= $this->totalDiscount(false);
474
        }
475
476
        $total += $this->taxTotal(false);
477
478
        return $this->formatMoney($total, null, null, $format);
479
    }
480
481
    /**
482
     * Gets the subtotal of the cart with or without tax
483
     *
484
     * @param boolean $format
485
     * @param boolean $withDiscount
486
     *
487
     * @return string
488
     */
489
    public function subTotal($format = true, $withDiscount = true)
490
    {
491
        $total = 0;
492
493
        if ($this->count() != 0) {
494
            foreach ($this->getItems() as $item) {
495
                $total += $item->subTotal(false, $withDiscount);
496
            }
497
        }
498
499
        return $this->formatMoney($total, null, null, $format);
500
    }
501
502
    /**
503
     * Get the count based on qty, or number of unique items
504
     *
505
     * @param bool $withItemQty
506
     *
507
     * @return int
508
     */
509
    public function count($withItemQty = true)
510
    {
511
        $count = 0;
512
513
        foreach ($this->getItems() as $item) {
514
            if ($withItemQty) {
515
                $count += $item->qty;
516
            } else {
517
                $count++;
518
            }
519
        }
520
521
        return $count;
522
    }
523
524
    /**
525
     *
526
     * Formats the number into a money format based on the locale and international formats
527
     *
528
     * @param $number
529
     * @param $locale
530
     * @param $internationalFormat
531
     * @param $format
532
     *
533
     * @return string
534
     */
535
    public static function formatMoney($number, $locale = null, $internationalFormat = null, $format = true)
536
    {
537
        $number = number_format($number, 2, '.', '');
538
539
        if ($format) {
540
            setlocale(LC_MONETARY, empty($locale) ? config('laracart.locale', 'en_US.UTF-8') : $locale);
541
542
            if (empty($internationalFormat) === true) {
543
                $internationalFormat = config('laracart.international_format', false);
544
            }
545
546
            $number = money_format($internationalFormat ? '%i' : '%n', $number);
547
        }
548
549
        return $number;
550
    }
551
552
    /**
553
     * Gets all the fee totals
554
     *
555
     * @param boolean $format
556
     *
557
     * @return string
558
     */
559
    public function feeTotals($format = true)
560
    {
561
        $feeTotal = 0;
562
563
        foreach ($this->getFees() as $fee) {
564
            $feeTotal += $fee->amount;
565
        }
566
567
        return $this->formatMoney($feeTotal, null, null, $format);
568
    }
569
570
    /**
571
     * Gets all the fees on the cart object
572
     *
573
     * @return mixed
574
     */
575
    public function getFees()
576
    {
577
        return $this->cart->fees;
578
    }
579
580
    /**
581
     * Gets the total amount discounted
582
     *
583
     * @param boolean $format
584
     *
585
     * @return string
586
     */
587
    public function totalDiscount($format = true)
588
    {
589
        $total = 0;
590
591
        foreach ($this->cart->coupons as $coupon) {
592
            if ($coupon->appliedToCart) {
593
                $total += $coupon->discount();
594
            }
595
        }
596
597
        return $this->formatMoney($total, null, null, $format);
598
    }
599
}
600