Completed
Push — master ( 9a2061...9f070b )
by Andrii
06:46
created

Period   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 86.67%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 46
ccs 13
cts 15
cp 0.8667
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getValue() 0 4 1
A fromString() 0 12 4
A ensureValidValue() 0 8 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\charge\modifiers\addons;
12
13
use hiqdev\php\billing\charge\modifiers\AddonInterface;
14
15
/**
16
 * Period addon.
17
 *
18
 * @author Andrii Vasyliev <[email protected]>
19
 */
20
abstract class Period implements AddonInterface
21
{
22
    /**
23
     * @var int
24
     */
25
    protected $value;
26
27 9
    public function __construct($value)
28
    {
29 9
        $this->value = static::ensureValidValue($value);
30 9
    }
31
32 2
    public function getValue()
33
    {
34 2
        return $this->value;
35
    }
36
37
    protected static $periods = [
38
        'month'     => MonthPeriod::class,
39
        'months'    => MonthPeriod::class,
40
        'year'      => YearPeriod::class,
41
        'years'     => YearPeriod::class,
42
    ];
43
44 9
    public static function fromString($string)
45
    {
46 9
        if (preg_match('/^((\d+) +)?(\w+)$/', trim($string), $ms)) {
47 9
            if (isset(static::$periods[$ms[3]])) {
48 9
                $class = static::$periods[$ms[3]];
49
50 9
                return new $class($ms[1] ?: 1);
51
            }
52
        }
53
54
        throw new \Exception("invalid period given: $string");
55
    }
56
57 9
    public static function ensureValidValue($value)
58
    {
59 9
        if (filter_var($value, FILTER_VALIDATE_INT) === false) {
60
            throw new \Exception('periodicity must be integer number');
61
        }
62
63 9
        return (int) $value;
64
    }
65
}
66