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

Period   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 86.67%

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getValue() 0 3 1
A fromString() 0 11 4
A ensureValidValue() 0 7 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 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