Passed
Push — master ( 15d4af...5593ee )
by Andrii
02:35
created

Period::fromString()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.074

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 3
nop 1
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
crap 4.074
rs 9.2
c 0
b 0
f 0
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 DateTimeImmutable;
14
use hiqdev\php\billing\charge\modifiers\AddonInterface;
15
use hiqdev\php\billing\formula\FormulaSemanticsError;
16
17
/**
18
 * Period addon.
19
 *
20
 * @author Andrii Vasyliev <[email protected]>
21
 */
22
abstract class Period implements AddonInterface
23
{
24
    /**
25
     * @var int
26
     */
27
    protected $value;
28
29 10
    public function __construct($value)
30
    {
31 10
        $this->value = static::ensureValidValue($value);
32 10
    }
33
34
    abstract public function countPeriodsPassed(DateTimeImmutable $since, DateTimeImmutable $time): float;
35
36 3
    public function getValue()
37
    {
38 3
        return $this->value;
39
    }
40
41
    protected static $periods = [
42
        'month'     => MonthPeriod::class,
43
        'months'    => MonthPeriod::class,
44
        'year'      => YearPeriod::class,
45
        'years'     => YearPeriod::class,
46
    ];
47
48 10
    public static function fromString($string)
49
    {
50 10
        if (preg_match('/^((\d+) +)?(\w+)$/', trim($string), $ms)) {
51 10
            if (isset(static::$periods[$ms[3]])) {
52 10
                $class = static::$periods[$ms[3]];
53
54 10
                return new $class($ms[1] ?: 1);
55
            }
56
        }
57
58
        throw new FormulaSemanticsError("invalid period given: $string");
59
    }
60
61 10
    public static function ensureValidValue($value)
62
    {
63 10
        if (filter_var($value, FILTER_VALIDATE_INT) === false) {
64
            throw new FormulaSemanticsError('periodicity must be integer number');
65
        }
66
67 10
        return (int) $value;
68
    }
69
}
70