1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ipag\Classes; |
4
|
|
|
|
5
|
|
|
use Ipag\Classes\Contracts\Emptiable; |
6
|
|
|
use Ipag\Classes\Contracts\ObjectSerializable; |
7
|
|
|
use Ipag\Classes\Traits\EmptiableTrait; |
8
|
|
|
|
9
|
|
|
final class Cart implements Emptiable, ObjectSerializable |
10
|
|
|
{ |
11
|
|
|
use EmptiableTrait; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @var array |
15
|
|
|
*/ |
16
|
|
|
private $products = []; |
17
|
|
|
|
18
|
|
|
public function __construct(array ...$products) |
19
|
|
|
{ |
20
|
|
|
$this->addProducts(...$products); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @return array |
25
|
|
|
*/ |
26
|
|
|
public function getProducts() |
27
|
|
|
{ |
28
|
|
|
if (empty($this->products)) { |
29
|
|
|
return []; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
return $this->products; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param Product $product |
37
|
|
|
*/ |
38
|
|
|
public function addProduct(Product $product) |
39
|
|
|
{ |
40
|
|
|
$this->products[] = $product; |
41
|
|
|
|
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param array |
47
|
|
|
*/ |
48
|
|
|
public function addProducts(array ...$products) |
49
|
|
|
{ |
50
|
|
|
foreach ($products as $product) { |
51
|
|
|
if (!empty($product)) { |
52
|
|
|
$this->addProduct((new Product()) |
53
|
|
|
->setName(isset($product[0]) ? $product[0] : '') |
54
|
|
|
->setUnitPrice(isset($product[1]) ? $product[1] : 0) |
55
|
|
|
->setQuantity(isset($product[2]) ? $product[2] : 1) |
56
|
|
|
->setSku(isset($product[3]) ? $product[3] : '') |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $this; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function serialize() |
65
|
|
|
{ |
66
|
|
|
if ($this->isEmpty()) { |
67
|
|
|
return []; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return [ |
71
|
|
|
'descricao_pedido' => urlencode(json_encode($this->serializeProducts())), |
72
|
|
|
]; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
private function serializeProducts() |
76
|
|
|
{ |
77
|
|
|
$_products = []; |
78
|
|
|
$productId = 1; |
79
|
|
|
|
80
|
|
|
foreach ($this->getProducts() as $product) { |
81
|
|
|
$_products[$productId++] = [ |
82
|
|
|
'descr' => $product->getName(), |
83
|
|
|
'valor' => $product->getUnitPrice(), |
84
|
|
|
'quant' => $product->getQuantity(), |
85
|
|
|
'id' => $product->getSku(), |
86
|
|
|
]; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return $_products; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|