1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace AppBundle\Cart; |
4
|
|
|
|
5
|
|
|
use AppBundle\Cart\getTotalPrice; |
6
|
|
|
use AppBundle\Entity\Meal; |
7
|
|
|
use AppBundle\Price\Price; |
8
|
|
|
|
9
|
|
|
class Cart |
10
|
|
|
{ |
11
|
|
|
private $rows = array(); |
12
|
|
|
|
13
|
|
|
public function getTotalCount() |
14
|
|
|
{ |
15
|
|
|
$total = 0; |
16
|
|
|
foreach ($this->rows as $row) { |
17
|
|
|
$total += $row->getQuantity(); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
return $total; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function getTotalPrice() |
24
|
|
|
{ |
25
|
|
|
$total = new Price('0'); |
26
|
|
|
foreach ($this->rows as $row) { |
27
|
|
|
$total = $total->add($row->getPrice()); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
return $total; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function isEmpty() |
34
|
|
|
{ |
35
|
|
|
return empty($this->rows); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function addRow(CartRow $row) |
39
|
|
|
{ |
40
|
|
|
$this->rows[] = $row; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function addMeal(Meal $meal, $quantity = 1) |
44
|
|
|
{ |
45
|
|
|
$found = null; |
46
|
|
|
foreach ($this->rows as $row) { |
47
|
|
|
if ($row->getMeal() === $meal) { |
48
|
|
|
$found = $row; |
49
|
|
|
|
50
|
|
|
break; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if ($found) { |
55
|
|
|
$row->addQuantity($quantity); |
|
|
|
|
56
|
|
|
|
57
|
|
|
return; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$row = new CartRow($meal, $quantity); |
61
|
|
|
$this->addRow($row); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function setMeal(Meal $meal, $quantity) |
65
|
|
|
{ |
66
|
|
|
if ($quantity == 0) { |
67
|
|
|
foreach ($this->rows as $i => $row) { |
68
|
|
|
if ($row->getMeal() !== $meal) { |
69
|
|
|
continue; |
70
|
|
|
} |
71
|
|
|
unset($this->rows[$i]); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
$found = null; |
78
|
|
|
foreach ($this->rows as $row) { |
79
|
|
|
if ($row->getMeal() === $meal) { |
80
|
|
|
$found = $row; |
81
|
|
|
|
82
|
|
|
break; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
if ($found) { |
87
|
|
|
$row->setQuantity($quantity); |
|
|
|
|
88
|
|
|
|
89
|
|
|
return; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
$row = new CartRow($meal, $quantity); |
93
|
|
|
$this->addRow($row); |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
public function getRows() |
97
|
|
|
{ |
98
|
|
|
return $this->rows; |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
public function toArray() |
102
|
|
|
{ |
103
|
|
|
$result = array( |
104
|
|
|
'total_count' => $this->getTotalCount(), |
105
|
|
|
'total_price' => $this->getTotalPrice()->toArray(), |
106
|
|
|
'rows' => array() |
107
|
|
|
); |
108
|
|
|
|
109
|
|
|
foreach ($this->rows as $row) { |
110
|
|
|
$result['rows'][] = $row->toArray(); |
111
|
|
|
} |
112
|
|
|
|
113
|
|
|
return $result; |
114
|
|
|
} |
115
|
|
|
} |
116
|
|
|
|
It seems like you are relying on a variable being defined by an iteration: