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

Cart::count()   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
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 12
    public static function make(): self
24
    {
25 12
        return new static();
26
    }
27
28
    /**
29
     * @param Product $product
30
     * @return static
31
     */
32 12
    public function addItem(Product $product): self
33
    {
34 12
        $this->items[] = $product;
35 12
        return $this;
36
    }
37
38
    /**
39
     * @param iterable $products
40
     * @return static
41
     */
42 2
    public function addItems(iterable $products): self
43
    {
44 2
        foreach ($products as $product) {
45 2
            $this->addItem($product);
46
        }
47
48 2
        return $this;
49
    }
50
51
    /**
52
     * @return Product[]
53
     */
54 12
    public function getItems(): array
55
    {
56 12
        return $this->items;
57
    }
58
59
    /**
60
     * The method returns the transfers already paid for the goods
61
     *
62
     * @param Customer $customer
63
     * @param bool|null $gifts
64
     * @return Transfer[]
65
     */
66 8
    public function alreadyBuy(Customer $customer, bool $gifts = null): array
67
    {
68 8
        $results = [];
69 8
        foreach ($this->getItems() as $item) {
70 8
            $transfer = $customer->paid($item, $gifts);
71 8
            if ($transfer) {
72 8
                $results[] = $transfer;
73
            }
74
        }
75
76 8
        return $results;
77
    }
78
79
    /**
80
     * @param Customer $customer
81
     * @param bool|null $force
82
     * @return bool
83
     */
84 11
    public function canBuy(Customer $customer, bool $force = null): bool
85
    {
86 11
        foreach ($this->items as $item) {
87 11
            if (!$item->canBuy($customer, $force)) {
88 11
                return false;
89
            }
90
        }
91
92 11
        return true;
93
    }
94
95
    /**
96
     * @return int
97
     */
98 1
    public function getTotal(): int
99
    {
100 1
        $result = 0;
101 1
        foreach ($this->items as $item) {
102 1
            $result += $item->getAmountProduct();
103
        }
104 1
        return $result;
105
    }
106
107
    /**
108
     * @return int
109
     */
110 8
    public function count(): int
111
    {
112 8
        return count($this->items);
113
    }
114
115
}
116