Completed
Pull Request — master (#40)
by Бабичев
07:33 queued 03:37
created

Cart::addItem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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