Completed
Pull Request — master (#40)
by Бабичев
05:10
created

Cart::make()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Bavix\Wallet\Objects;
4
5
use Bavix\Wallet\Interfaces\Customer;
6
use Bavix\Wallet\Interfaces\Product;
7
8
class Cart
9
{
10
11
    /**
12
     * @var Product[]
13
     */
14
    protected $items = [];
15
16
    /**
17
     * @return static
18
     */
19 10
    public static function make(): self
20
    {
21 10
        return new static();
22
    }
23
24
    /**
25
     * @param Product $product
26
     * @return static
27
     */
28 10
    public function addItem(Product $product): self
29
    {
30 10
        $this->items[] = $product;
31 10
        return $this;
32
    }
33
34
    /**
35
     * @return Product[]
36
     */
37 10
    public function getItems(): array
38
    {
39 10
        return $this->items;
40
    }
41
42
    /**
43
     * @param Customer $customer
44
     * @param bool|null $force
45
     * @return bool
46
     */
47
    public function canBuy(Customer $customer, bool $force = null): bool
48
    {
49
        foreach ($this->items as $item) {
50
            if (!$item->canBuy($customer, $force)) {
51
                return false;
52
            }
53
        }
54
        
55
        return true;
56
    }
57
58
    /**
59
     * @return int
60
     */
61
    public function getTotal(): int
62
    {
63
        $result = 0;
64
        foreach ($this->items as $item) {
65
            $result += $item->getAmountProduct();
66
        }
67
        return $result;
68
    }
69
70
    /**
71
     * @return array|null
72
     */
73
    public function getMeta(): ?array
74
    {
75
        $meta = [];
76
        foreach ($this->items as $item) {
77
            $data = $item->getMetaProduct();
78
            if ($data) {
79
                $meta[] = $data;
80
            }
81
        }
82
83
        if (empty($meta)) {
84
            return null;
85
        }
86
87
        return $meta;
88
    }
89
90
}
91