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

Cart::canBuy()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 2
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 3
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
use Bavix\Wallet\Models\Transfer;
8
use Countable;
9
use Illuminate\Database\Eloquent\ModelNotFoundException;
10
use function count;
11
12
class Cart implements Countable
13
{
14
15
    /**
16
     * @var Product[]
17
     */
18
    protected $items = [];
19
20
    /**
21
     * @return static
22
     */
23 11
    public static function make(): self
24
    {
25 11
        return new static();
26
    }
27
28
    /**
29
     * @param Product $product
30
     * @return static
31
     */
32 11
    public function addItem(Product $product): self
33
    {
34 11
        $this->items[] = $product;
35 11
        return $this;
36
    }
37
38
    /**
39
     * @param iterable $products
40
     * @return static
41
     */
42 1
    public function addItems(iterable $products): self
43
    {
44 1
        foreach ($products as $product) {
45 1
            $this->addItem($product);
46
        }
47
48 1
        return $this;
49
    }
50
51
    /**
52
     * @return Product[]
53
     */
54 11
    public function getItems(): array
55
    {
56 11
        return $this->items;
57
    }
58
59
    /**
60
     *
61
     *
62
     * @param Customer $customer
63
     * @param bool|null $gifts
64
     * @return Transfer[]
65
     */
66 7
    public function alreadyBuy(Customer $customer, bool $gifts = null): array
67
    {
68 7
        $results = [];
69 7
        foreach ($this->getItems() as $item) {
70 7
            $transfer = $customer->paid($item, $gifts);
71 7
            $results[] = $transfer;
72
        }
73
74 7
        return $results;
75
    }
76
77
    /**
78
     * @param Customer $customer
79
     * @param bool|null $force
80
     * @return bool
81
     */
82 10
    public function canBuy(Customer $customer, bool $force = null): bool
83
    {
84 10
        foreach ($this->items as $item) {
85 10
            if (!$item->canBuy($customer, $force)) {
86 10
                return false;
87
            }
88
        }
89
90 10
        return true;
91
    }
92
93
    /**
94
     * @return int
95
     */
96 1
    public function getTotal(): int
97
    {
98 1
        $result = 0;
99 1
        foreach ($this->items as $item) {
100 1
            $result += $item->getAmountProduct();
101
        }
102 1
        return $result;
103
    }
104
105
    /**
106
     * @return int
107
     */
108 1
    public function count(): int
109
    {
110 1
        return count($this->items);
111
    }
112
113
}
114