1: | <?php |
2: | |
3: | namespace Mypos\IPC; |
4: | |
5: | /** |
6: | * Purchase cart object |
7: | */ |
8: | class Cart |
9: | { |
10: | const ITEM_TYPE_ARTICLE = 'article'; |
11: | const ITEM_TYPE_DELIVERY = 'delivery'; |
12: | const ITEM_TYPE_DISCOUNT = 'discount'; |
13: | |
14: | /** |
15: | * Array containing cart items |
16: | * |
17: | * @var array |
18: | */ |
19: | private $cart; |
20: | |
21: | /** |
22: | * |
23: | * @param string $itemName Item name |
24: | * @param int $quantity Items quantity |
25: | * @param float $price Single item price |
26: | * |
27: | * @param string $type |
28: | * @return Cart |
29: | * @throws IPC_Exception |
30: | */ |
31: | public function add($itemName, $quantity, $price, $type = self::ITEM_TYPE_ARTICLE) |
32: | { |
33: | if (empty($itemName)) { |
34: | throw new IPC_Exception('Invalid cart item name'); |
35: | } |
36: | |
37: | if (empty($quantity) || !Helper::isValidCartQuantity($quantity)) { |
38: | throw new IPC_Exception('Invalid cart item quantity'); |
39: | } |
40: | |
41: | if (empty($price) || !Helper::isValidAmount($price)) { |
42: | throw new IPC_Exception('Invalid cart item price'); |
43: | } |
44: | |
45: | $item = [ |
46: | 'name' => $itemName, |
47: | 'quantity' => $quantity, |
48: | 'price' => $price, |
49: | ]; |
50: | |
51: | switch ($type) { |
52: | case self::ITEM_TYPE_DELIVERY: |
53: | $item['delivery'] = 1; |
54: | break; |
55: | case self::ITEM_TYPE_DISCOUNT: |
56: | $item['price'] = $num = -1 * abs($item['price']); |
57: | break; |
58: | } |
59: | |
60: | $this->cart[] = $item; |
61: | |
62: | return $this; |
63: | } |
64: | |
65: | /** |
66: | * Returns cart total amount |
67: | * |
68: | * @return float |
69: | */ |
70: | public function getTotal() |
71: | { |
72: | $sum = 0; |
73: | if (!empty($this->cart)) { |
74: | foreach ($this->cart as $v) { |
75: | $sum += $v['quantity'] * $v['price']; |
76: | } |
77: | } |
78: | |
79: | return $sum; |
80: | } |
81: | |
82: | /** |
83: | * Returns count of items in cart |
84: | * |
85: | * @return int |
86: | */ |
87: | public function getItemsCount() |
88: | { |
89: | return (is_array($this->cart) && !empty($this->cart)) ? count($this->cart) : 0; |
90: | } |
91: | |
92: | /** |
93: | * Validate cart items |
94: | * |
95: | * @return boolean |
96: | * @throws IPC_Exception |
97: | */ |
98: | public function validate() |
99: | { |
100: | if (!$this->getCart() || count($this->getCart()) == 0) { |
101: | throw new IPC_Exception('Missing cart items'); |
102: | } |
103: | |
104: | return true; |
105: | } |
106: | |
107: | /** |
108: | * Return cart array |
109: | * |
110: | * @return array |
111: | */ |
112: | public function getCart() |
113: | { |
114: | return $this->cart; |
115: | } |
116: | } |
117: |