Completed
Push — master ( a88c1a...2a7402 )
by Andrii
02:44
created

Billing::getRepoAggregator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
1
<?php
2
/**
3
 * PHP Billing Library
4
 *
5
 * @link      https://github.com/hiqdev/php-billing
6
 * @package   php-billing
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\php\billing\order;
12
13
use hiqdev\php\billing\bill\BillRepositoryInterface;
14
use hiqdev\php\billing\tools\AggregatorInterface;
15
use hiqdev\php\billing\tools\MergerInterface;
16
use hiqdev\php\billing\tools\DbMergingAggregator;
17
18
/**
19
 * Billing calculates and saves bills for given order.
20
 *
21
 * @author Andrii Vasyliev <[email protected]>
22
 */
23
class Billing implements BillingInterface
24
{
25
    /**
26
     * @var CalculatorInterface
27
     */
28
    protected $calculator;
29
    /**
30
     * @var AggregatorInterface
31
     */
32
    protected $aggregator;
33
    /**
34
     * @var AggregatorInterface
35
     */
36
    protected $repoAggregator;
37
    /**
38
     * @var MergerInterface
39
     */
40
    protected $merger;
41
    /**
42
     * @var BillRepositoryInterface
43
     */
44
    protected $repository;
45
46
    public function __construct(
47
        CalculatorInterface $calculator,
48
        AggregatorInterface $aggregator,
49
        MergerInterface $merger,
50
        ?BillRepositoryInterface $repository
51
    ) {
52
        $this->calculator = $calculator;
53
        $this->aggregator = $aggregator;
54
        $this->merger = $merger;
55
        $this->repository = $repository;
56
    }
57
58
    public function calculate(OrderInterface $order): array
59
    {
60
        $charges = $this->calculator->calculateOrder($order);
61
        $bills = $this->aggregator->aggregateCharges($charges);
62
63
        return $this->merger->mergeBills($bills);
64
    }
65
66
    public function perform(OrderInterface $order): array
67
    {
68
        $charges = $this->calculator->calculateOrder($order);
69
        $bills = $this->getRepoAggregator()->aggregateCharges($charges);
70
71
        return $this->saveBills($bills);
72
    }
73
74
    private function getRepoAggregator(): AggregatorInterface
75
    {
76
        if ($this->repoAggregator === null) {
77
            $this->repoAggregator = new DbMergingAggregator($this->aggregator, $this->repository, $this->merger);
78
        }
79
80
        return $this->repoAggregator;
81
    }
82
83
    /**
84
     * @param BillInterface[] $bills
85
     * @return BillInterface[]
86
     */
87
    private function saveBills(array $bills): array
88
    {
89
        $res = [];
90
        foreach ($bills as $key => $bill) {
91
            $res[$key] = $this->repository->save($bill);
92
        }
93
94
        return $res;
95
    }
96
}
97