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
|
|
|
|