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

Period::ensureValidValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 4
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2.0625
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