GroupByClientMerger   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 17
c 1
b 0
f 0
dl 0
loc 52
ccs 0
cts 18
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A mergeBills() 0 14 3
A __construct() 0 4 1
A mergeBill() 0 6 1
1
<?php
2
3
namespace hiqdev\billing\hiapi\tools;
4
5
use hiqdev\php\billing\bill\BillInterface;
6
use hiqdev\php\billing\tools\MergerInterface;
7
8
/**
9
 * Class GroupByClientMerger merges bills by the buyer.
10
 *
11
 * Could be used to get totals by client in a list of bills.
12
 *
13
 * @author Dmytro Naumenko <[email protected]>
14
 */
15
final class GroupByClientMerger implements MergerInterface
16
{
17
    private const CUSTOMER_UNKNOWN = 'guest';
18
19
    /**
20
     * @var MergerInterface
21
     */
22
    private $defaultMerger;
23
    /**
24
     * @var MonthlyBillQuantityFixer
25
     */
26
    private $monthlyBillQuantityFixer;
27
28
    public function __construct(MergerInterface $defaultMergingStrategy, MonthlyBillQuantityFixer $monthlyBillQuantityFixer)
29
    {
30
        $this->defaultMerger = $defaultMergingStrategy;
31
        $this->monthlyBillQuantityFixer = $monthlyBillQuantityFixer;
32
    }
33
34
    /**
35
     * Merges array of bills.
36
     * @param BillInterface[] $bills
37
     * @return BillInterface[]
38
     */
39
    public function mergeBills(array $bills): array
40
    {
41
        $res = [];
42
        foreach ($bills as $bill) {
43
            $buyer = $bill->getCustomer()->getUniqueId() ?? self::CUSTOMER_UNKNOWN;
44
45
            if (empty($res[$buyer])) {
46
                $res[$buyer] = $bill;
47
            } else {
48
                $res[$buyer] = $this->mergeBill($res[$buyer], $bill);
49
            }
50
        }
51
52
        return $res;
53
    }
54
55
    /**
56
     * Merges two bills in one.
57
     * @param BillInterface $first
58
     * @param BillInterface $other
59
     * @return BillInterface
60
     */
61
    public function mergeBill(BillInterface $first, BillInterface $other): BillInterface
62
    {
63
        $bill = $this->defaultMerger->mergeBill($first, $other);
64
        $this->monthlyBillQuantityFixer->__invoke($bill);
65
66
        return $bill;
67
    }
68
}
69