Completed
Push — master ( eebd57...9e79a2 )
by Andrii
07:00
created

FormulaEngine::getDiscount()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
ccs 4
cts 4
cp 1
cc 2
eloc 4
nc 2
nop 0
crap 2
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\formula;
12
13
use hiqdev\php\billing\charge\ChargeModifier;
14
use hiqdev\php\billing\charge\modifiers\Discount;
15
use hiqdev\php\billing\charge\modifiers\Leasing;
16
use Hoa\Ruler\Context;
17
use Hoa\Ruler\Ruler;
18
19
/**
20
 * @author Andrii Vasyliev <[email protected]>
21
 */
22
class FormulaEngine
23
{
24
    protected $ruler;
25
26
    protected $asserter;
27
28
    protected $context;
29
30
    protected $discount;
31
32
    protected $leasing;
33
34 2
    public function __construct()
35
    {
36 2
        if (!class_exists(Context::class)) {
37
            throw new \Exception('to use formula engine install `hoa/ruler`');
38
        }
39 2
    }
40
41
    /**
42
     * @param string $formula
43
     * @return ChargeModifier
44
     */
45 2
    public function build(string $formula): ChargeModifier
46
    {
47 2
        $formula = strtr(trim($formula), ["\n" => ' AND ']);
48
49 2
        return $this->getRuler()->assert($formula, $this->getContext());
50
    }
51
52 2
    public function getRuler()
53
    {
54 2
        if ($this->ruler === null) {
55 2
            $this->ruler = new Ruler();
56 2
            $this->ruler->setAsserter($this->getAsserter());
57
        }
58
59 2
        return $this->ruler;
60
    }
61
62 2
    public function getAsserter()
63
    {
64 2
        if ($this->asserter === null) {
65 2
            $this->asserter = new Asserter();
66
        }
67
68 2
        return $this->asserter;
69
    }
70
71 2
    public function getContext()
72
    {
73 2
        if ($this->context === null) {
74 2
            $this->context = $this->buildContext();
75
        }
76
77 2
        return $this->context;
78
    }
79
80 2
    protected function buildContext()
81
    {
82 2
        $context = new Context();
83 2
        $context['discount'] = $this->getDiscount();
84 2
        $context['leasing'] = $this->getLeasing();
85
86 2
        return $context;
87
    }
88
89 2
    public function getDiscount()
90
    {
91 2
        if ($this->discount === null) {
92 2
            $this->discount = new Discount();
93
        }
94
95 2
        return $this->discount;
96
    }
97
98 2
    public function getLeasing()
99
    {
100 2
        if ($this->leasing === null) {
101 2
            $this->leasing = new Leasing();
102
        }
103
104 2
        return $this->leasing;
105
    }
106
}
107