-
Notifications
You must be signed in to change notification settings - Fork 463
/
Copy pathCart.php
881 lines (741 loc) · 24 KB
/
Cart.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
<?php namespace Darryldecode\Cart;
use Darryldecode\Cart\Exceptions\InvalidConditionException;
use Darryldecode\Cart\Exceptions\InvalidItemException;
use Darryldecode\Cart\Helpers\Helpers;
use Darryldecode\Cart\Validators\CartItemValidator;
use Darryldecode\Cart\Exceptions\UnknownModelException;
/**
* Class Cart
* @package Darryldecode\Cart
*/
class Cart
{
/**
* the item storage
*
* @var
*/
protected $session;
/**
* the event dispatcher
*
* @var
*/
protected $events;
/**
* the cart session key
*
* @var
*/
protected $instanceName;
/**
* the session key use for the cart
*
* @var
*/
protected $sessionKey;
/**
* the session key use to persist cart items
*
* @var
*/
protected $sessionKeyCartItems;
/**
* the session key use to persist cart conditions
*
* @var
*/
protected $sessionKeyCartConditions;
/**
* Configuration to pass to ItemCollection
*
* @var
*/
protected $config;
/**
* This holds the currently added item id in cart for association
*
* @var
*/
protected $currentItemId;
/**
* our object constructor
*
* @param $session
* @param $events
* @param $instanceName
* @param $session_key
* @param $config
*/
public function __construct($session, $events, $instanceName, $session_key, $config)
{
$this->events = $events;
$this->session = $session;
$this->instanceName = $instanceName;
$this->sessionKey = $session_key;
$this->sessionKeyCartItems = $this->sessionKey . '_cart_items';
$this->sessionKeyCartConditions = $this->sessionKey . '_cart_conditions';
$this->config = $config;
$this->currentItemId = null;
$this->fireEvent('created');
}
/**
* sets the session key
*
* @param string $sessionKey the session key or identifier
* @return $this|bool
* @throws \Exception
*/
public function session($sessionKey)
{
if (!$sessionKey) throw new \Exception("Session key is required.");
$this->sessionKey = $sessionKey;
$this->sessionKeyCartItems = $this->sessionKey . '_cart_items';
$this->sessionKeyCartConditions = $this->sessionKey . '_cart_conditions';
return $this;
}
/**
* get instance name of the cart
*
* @return string
*/
public function getInstanceName()
{
return $this->instanceName;
}
/**
* get an item on a cart by item ID
*
* @param $itemId
* @return mixed
*/
public function get($itemId)
{
return $this->getContent()->get($itemId);
}
/**
* check if an item exists by item ID
*
* @param $itemId
* @return bool
*/
public function has($itemId)
{
return $this->getContent()->has($itemId);
}
/**
* add item to the cart, it can be an array or multi dimensional array
*
* @param string|array $id
* @param string $name
* @param float $price
* @param int $quantity
* @param array $attributes
* @param CartCondition|array $conditions
* @param string $associatedModel
* @return $this
* @throws InvalidItemException
*/
public function add($id, $name = null, $price = null, $quantity = null, $attributes = [], $conditions = [], $associatedModel = null)
{
// if the first argument is an array,
// we will need to call add again
if (is_array($id)) {
// the first argument is an array, now we will need to check if it is a multi dimensional
// array, if so, we will iterate through each item and call add again
if (Helpers::isMultiArray($id)) {
foreach ($id as $item) {
$this->add(
$item['id'],
$item['name'],
$item['price'],
$item['quantity'],
Helpers::issetAndHasValueOrAssignDefault($item['attributes'], []),
Helpers::issetAndHasValueOrAssignDefault($item['conditions'], []),
Helpers::issetAndHasValueOrAssignDefault($item['associatedModel'], null)
);
}
} else {
$this->add(
$id['id'],
$id['name'],
$id['price'],
$id['quantity'],
Helpers::issetAndHasValueOrAssignDefault($id['attributes'], []),
Helpers::issetAndHasValueOrAssignDefault($id['conditions'], []),
Helpers::issetAndHasValueOrAssignDefault($id['associatedModel'], null)
);
}
return $this;
}
$data = array(
'id' => $id,
'name' => $name,
'price' => Helpers::normalizePrice($price),
'quantity' => $quantity,
'attributes' => new ItemAttributeCollection($attributes),
'conditions' => $conditions
);
if (isset($associatedModel) && $associatedModel != '') {
$data['associatedModel'] = $associatedModel;
}
// validate data
$item = $this->validate($data);
// get the cart
$cart = $this->getContent();
// if the item is already in the cart we will just update it
if ($cart->has($id)) {
$this->update($id, $item);
} else {
$this->addRow($id, $item);
}
$this->currentItemId = $id;
return $this;
}
/**
* update a cart
*
* @param $id
* @param array $data
*
* the $data will be an associative array, you don't need to pass all the data, only the key value
* of the item you want to update on it
* @return bool
*/
public function update($id, $data)
{
if ($this->fireEvent('updating', $data) === false) {
return false;
}
$cart = $this->getContent();
$item = $cart->pull($id);
foreach ($data as $key => $value) {
// if the key is currently "quantity" we will need to check if an arithmetic
// symbol is present so we can decide if the update of quantity is being added
// or being reduced.
if ($key == 'quantity') {
// we will check if quantity value provided is array,
// if it is, we will need to check if a key "relative" is set
// and we will evaluate its value if true or false,
// this tells us how to treat the quantity value if it should be updated
// relatively to its current quantity value or just totally replace the value
if (is_array($value)) {
if (isset($value['relative'])) {
if ((bool)$value['relative']) {
$item = $this->updateQuantityRelative($item, $key, $value['value']);
} else {
$item = $this->updateQuantityNotRelative($item, $key, $value['value']);
}
}
} else {
$item = $this->updateQuantityRelative($item, $key, $value);
}
} elseif ($key == 'attributes') {
$item[$key] = new ItemAttributeCollection($value);
} else {
$item[$key] = $value;
}
}
$cart->put($id, $item);
$this->save($cart);
$this->fireEvent('updated', $item);
return true;
}
/**
* add condition on an existing item on the cart
*
* @param int|string $productId
* @param CartCondition $itemCondition
* @return $this
*/
public function addItemCondition($productId, $itemCondition)
{
if ($product = $this->get($productId)) {
$conditionInstance = "\\Darryldecode\\Cart\\CartCondition";
if ($itemCondition instanceof $conditionInstance) {
// we need to copy first to a temporary variable to hold the conditions
// to avoid hitting this error "Indirect modification of overloaded element of Darryldecode\Cart\ItemCollection has no effect"
// this is due to laravel Collection instance that implements Array Access
// // see link for more info: http://stackoverflow.com/questions/20053269/indirect-modification-of-overloaded-element-of-splfixedarray-has-no-effect
$itemConditionTempHolder = $product['conditions'];
if (is_array($itemConditionTempHolder)) {
array_push($itemConditionTempHolder, $itemCondition);
} else {
$itemConditionTempHolder = $itemCondition;
}
$this->update($productId, array(
'conditions' => $itemConditionTempHolder // the newly updated conditions
));
}
}
return $this;
}
/**
* removes an item on cart by item ID
*
* @param $id
* @return bool
*/
public function remove($id)
{
$cart = $this->getContent();
if ($this->fireEvent('removing', $id) === false) {
return false;
}
$cart->forget($id);
$this->save($cart);
$this->fireEvent('removed', $id);
return true;
}
/**
* clear cart
* @return bool
*/
public function clear()
{
if ($this->fireEvent('clearing') === false) {
return false;
}
$this->session->put(
$this->sessionKeyCartItems,
[]
);
$this->fireEvent('cleared');
return true;
}
/**
* add a condition on the cart
*
* @param CartCondition|array $condition
* @return $this
* @throws InvalidConditionException
*/
public function condition($condition)
{
if (is_array($condition)) {
foreach ($condition as $c) {
$this->condition($c);
}
return $this;
}
if (!$condition instanceof CartCondition) throw new InvalidConditionException('Argument 1 must be an instance of \'Darryldecode\Cart\CartCondition\'');
$conditions = $this->getConditions();
// Check if order has been applied
if ($condition->getOrder() == 0) {
$last = $conditions->last();
$condition->setOrder(!is_null($last) ? $last->getOrder() + 1 : 1);
}
$conditions->put($condition->getName(), $condition);
$conditions = $conditions->sortBy(function ($condition, $key) {
return $condition->getOrder();
});
$this->saveConditions($conditions);
return $this;
}
/**
* get conditions applied on the cart
*
* @return CartConditionCollection
*/
public function getConditions()
{
return new CartConditionCollection($this->session->get($this->sessionKeyCartConditions));
}
/**
* get condition applied on the cart by its name
*
* @param $conditionName
* @return CartCondition
*/
public function getCondition($conditionName)
{
return $this->getConditions()->get($conditionName);
}
/**
* Get all the condition filtered by Type
* Please Note that this will only return condition added on cart bases, not those conditions added
* specifically on an per item bases
*
* @param $type
* @return CartConditionCollection
*/
public function getConditionsByType($type)
{
return $this->getConditions()->filter(function (CartCondition $condition) use ($type) {
return $condition->getType() == $type;
});
}
/**
* Remove all the condition with the $type specified
* Please Note that this will only remove condition added on cart bases, not those conditions added
* specifically on an per item bases
*
* @param $type
* @return $this
*/
public function removeConditionsByType($type)
{
$this->getConditionsByType($type)->each(function ($condition) {
$this->removeCartCondition($condition->getName());
});
}
/**
* removes a condition on a cart by condition name,
* this can only remove conditions that are added on cart bases not conditions that are added on an item/product.
* If you wish to remove a condition that has been added for a specific item/product, you may
* use the removeItemCondition(itemId, conditionName) method instead.
*
* @param $conditionName
* @return void
*/
public function removeCartCondition($conditionName)
{
$conditions = $this->getConditions();
$conditions->pull($conditionName);
$this->saveConditions($conditions);
}
/**
* remove a condition that has been applied on an item that is already on the cart
*
* @param $itemId
* @param $conditionName
* @return bool
*/
public function removeItemCondition($itemId, $conditionName)
{
if (!$item = $this->getContent()->get($itemId)) {
return false;
}
if ($this->itemHasConditions($item)) {
// NOTE:
// we do it this way, we get first conditions and store
// it in a temp variable $originalConditions, then we will modify the array there
// and after modification we will store it again on $item['conditions']
// This is because of ArrayAccess implementation
// see link for more info: http://stackoverflow.com/questions/20053269/indirect-modification-of-overloaded-element-of-splfixedarray-has-no-effect
$tempConditionsHolder = $item['conditions'];
// if the item's conditions is in array format
// we will iterate through all of it and check if the name matches
// to the given name the user wants to remove, if so, remove it
if (is_array($tempConditionsHolder)) {
foreach ($tempConditionsHolder as $k => $condition) {
if ($condition->getName() == $conditionName) {
unset($tempConditionsHolder[$k]);
}
}
$item['conditions'] = $tempConditionsHolder;
}
// if the item condition is not an array, we will check if it is
// an instance of a Condition, if so, we will check if the name matches
// on the given condition name the user wants to remove, if so,
// lets just make $item['conditions'] an empty array as there's just 1 condition on it anyway
else {
$conditionInstance = "Darryldecode\\Cart\\CartCondition";
if ($item['conditions'] instanceof $conditionInstance) {
if ($tempConditionsHolder->getName() == $conditionName) {
$item['conditions'] = [];
}
}
}
}
$this->update($itemId, array(
'conditions' => $item['conditions']
));
return true;
}
/**
* remove all conditions that has been applied on an item that is already on the cart
*
* @param $itemId
* @return bool
*/
public function clearItemConditions($itemId)
{
if (!$item = $this->getContent()->get($itemId)) {
return false;
}
$this->update($itemId, array(
'conditions' => []
));
return true;
}
/**
* clears all conditions on a cart,
* this does not remove conditions that has been added specifically to an item/product.
* If you wish to remove a specific condition to a product, you may use the method: removeItemCondition($itemId, $conditionName)
*
* @return void
*/
public function clearCartConditions()
{
$this->session->put(
$this->sessionKeyCartConditions,
[]
);
}
/**
* get cart sub total without conditions
* @param bool $formatted
* @return float
*/
public function getSubTotalWithoutConditions($formatted = true)
{
$cart = $this->getContent();
$sum = $cart->sum(function ($item) {
return $item->getPriceSum();
});
return Helpers::formatValue(floatval($sum), $formatted, $this->config);
}
/**
* get cart sub total
* @param bool $formatted
* @return float
*/
public function getSubTotal($formatted = true)
{
$cart = $this->getContent();
$sum = $cart->sum(function (ItemCollection $item) {
return $item->getPriceSumWithConditions(false);
});
// get the conditions that are meant to be applied
// on the subtotal and apply it here before returning the subtotal
$conditions = $this
->getConditions()
->filter(function (CartCondition $cond) {
return $cond->getTarget() === 'subtotal';
});
// if there is no conditions, lets just return the sum
if (!$conditions->count()) return Helpers::formatValue(floatval($sum), $formatted, $this->config);
// there are conditions, lets apply it
$newTotal = 0.00;
$process = 0;
$conditions->each(function (CartCondition $cond) use ($sum, &$newTotal, &$process) {
// if this is the first iteration, the toBeCalculated
// should be the sum as initial point of value.
$toBeCalculated = ($process > 0) ? $newTotal : $sum;
$newTotal = $cond->applyCondition($toBeCalculated);
$process++;
});
return Helpers::formatValue(floatval($newTotal), $formatted, $this->config);
}
/**
* the new total in which conditions are already applied
*
* @return float
*/
public function getTotal()
{
$subTotal = $this->getSubTotal(false);
$newTotal = 0.00;
$process = 0;
$conditions = $this
->getConditions()
->filter(function (CartCondition $cond) {
return $cond->getTarget() === 'total';
});
// if no conditions were added, just return the sub total
if (!$conditions->count()) {
return Helpers::formatValue($subTotal, $this->config['format_numbers'], $this->config);
}
$conditions
->each(function (CartCondition $cond) use ($subTotal, &$newTotal, &$process) {
$toBeCalculated = ($process > 0) ? $newTotal : $subTotal;
$newTotal = $cond->applyCondition($toBeCalculated);
$process++;
});
return Helpers::formatValue($newTotal, $this->config['format_numbers'], $this->config);
}
/**
* get total quantity of items in the cart
*
* @return int
*/
public function getTotalQuantity()
{
$items = $this->getContent();
if ($items->isEmpty()) return 0;
$count = $items->sum(function ($item) {
return $item['quantity'];
});
return $count;
}
/**
* get the cart
*
* @return CartCollection
*/
public function getContent()
{
return (new CartCollection($this->session->get($this->sessionKeyCartItems)))->reject(function($item) {
return ! ($item instanceof ItemCollection);
});
}
/**
* check if cart is empty
*
* @return bool
*/
public function isEmpty()
{
return $this->getContent()->isEmpty();
}
/**
* validate Item data
*
* @param $item
* @return array $item;
* @throws InvalidItemException
*/
protected function validate($item)
{
$rules = array(
'id' => 'required',
'price' => 'required|numeric',
'quantity' => 'required|numeric|min:0.1',
'name' => 'required',
);
$validator = CartItemValidator::make($item, $rules);
if ($validator->fails()) {
throw new InvalidItemException($validator->messages()->first());
}
return $item;
}
/**
* add row to cart collection
*
* @param $id
* @param $item
* @return bool
*/
protected function addRow($id, $item)
{
if ($this->fireEvent('adding', $item) === false) {
return false;
}
$cart = $this->getContent();
$cart->put($id, new ItemCollection($item, $this->config));
$this->save($cart);
$this->fireEvent('added', $item);
return true;
}
/**
* save the cart
*
* @param $cart CartCollection
*/
protected function save($cart)
{
$this->session->put($this->sessionKeyCartItems, $cart);
}
/**
* save the cart conditions
*
* @param $conditions
*/
protected function saveConditions($conditions)
{
$this->session->put($this->sessionKeyCartConditions, $conditions);
}
/**
* check if an item has condition
*
* @param $item
* @return bool
*/
protected function itemHasConditions($item)
{
if (!isset($item['conditions'])) return false;
if (is_array($item['conditions'])) {
return count($item['conditions']) > 0;
}
$conditionInstance = "Darryldecode\\Cart\\CartCondition";
if ($item['conditions'] instanceof $conditionInstance) return true;
return false;
}
/**
* update a cart item quantity relative to its current quantity
*
* @param $item
* @param $key
* @param $value
* @return mixed
*/
protected function updateQuantityRelative($item, $key, $value)
{
if (preg_match('/\-/', $value) == 1) {
$value = (int)str_replace('-', '', $value);
// we will not allowed to reduced quantity to 0, so if the given value
// would result to item quantity of 0, we will not do it.
if (($item[$key] - $value) > 0) {
$item[$key] -= $value;
}
} elseif (preg_match('/\+/', $value) == 1) {
$item[$key] += (int)str_replace('+', '', $value);
} else {
$item[$key] += (int)$value;
}
return $item;
}
/**
* update cart item quantity not relative to its current quantity value
*
* @param $item
* @param $key
* @param $value
* @return mixed
*/
protected function updateQuantityNotRelative($item, $key, $value)
{
$item[$key] = (int)$value;
return $item;
}
/**
* Setter for decimals. Change value on demand.
* @param $decimals
*/
public function setDecimals($decimals)
{
$this->decimals = $decimals;
}
/**
* Setter for decimals point. Change value on demand.
* @param $dec_point
*/
public function setDecPoint($dec_point)
{
$this->dec_point = $dec_point;
}
public function setThousandsSep($thousands_sep)
{
$this->thousands_sep = $thousands_sep;
}
/**
* @param $name
* @param $value
* @return mixed
*/
protected function fireEvent($name, $value = [])
{
return $this->events->dispatch($this->getInstanceName() . '.' . $name, array_values([$value, $this]), true);
}
/**
* Associate the cart item with the given id with the given model.
*
* @param string $id
* @param mixed $model
*
* @return void
*/
public function associate($model)
{
if (is_string($model) && !class_exists($model)) {
throw new UnknownModelException("The supplied model {$model} does not exist.");
}
$cart = $this->getContent();
$item = $cart->pull($this->currentItemId);
$item['associatedModel'] = $model;
$cart->put($this->currentItemId, new ItemCollection($item, $this->config));
$this->save($cart);
return $this;
}
}