Completed
Push — master ( 7d972a...3baf5c )
by Andrii
02:11
created

Discount   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 3

Test Coverage

Coverage 85%

Importance

Changes 0
Metric Value
wmc 10
lcom 2
cbo 3
dl 0
loc 51
ccs 17
cts 20
cp 0.85
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getValue() 0 4 1
A isAbsolute() 0 4 1
C ensureValidValue() 0 23 7
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\charge\modifiers\addons;
12
13
use hiqdev\php\billing\charge\modifiers\AddonInterface;
14
use Money\Currencies\ISOCurrencies;
15
use Money\Currency;
16
use Money\Money;
17
use Money\Parser\DecimalMoneyParser;
18
19
/**
20
 * Discount addon.
21
 *
22
 * @author Andrii Vasyliev <[email protected]>
23
 */
24
class Discount implements AddonInterface
25
{
26
    protected static $name = 'discount';
27
28
    /**
29
     * @var string|Money
30
     */
31
    protected $value;
32
33
    protected $moneyParser;
34
35 11
    public function __construct($value)
36
    {
37 11
        $this->moneyParser = new DecimalMoneyParser(new ISOCurrencies());
38 11
        $this->value = $this->ensureValidValue($value);
39 11
    }
40
41 9
    public function getValue()
42
    {
43 9
        return $this->value;
44
    }
45
46 9
    public function isAbsolute()
47
    {
48 9
        return $this->value instanceof Money;
49
    }
50
51 11
    public function ensureValidValue($value)
52
    {
53 11
        if ($value instanceof Money) {
54 4
            return $value;
55
        }
56
57 9
        if (is_numeric($value)) {
58 6
            return (string) $value;
59
        }
60
61 5
        if (is_string($value) && preg_match('/^(\d{1,5}(\.\d+)?)%$/', $value, $ms)) {
62 3
            return $ms[1];
63
        }
64
65 2
        if (is_string($value) && preg_match('/^(\d{1,5}(\.\d+)?) ([A-Z]{3})$/', $value, $ms)) {
66 2
            return $this->moneyParser->parse($ms[1], new Currency($ms[3]));
67
        }
68
69
        /// TODO: add special exception
70
        var_dump($value);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($value); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
71
        $name = static::$name;
72
        throw new \Exception("invalid $name value: $value");
73
    }
74
}
75