|
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-2020, 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
|
|
|
'day' => DayPeriod::class, |
|
43
|
|
|
'days' => DayPeriod::class, |
|
44
|
|
|
'month' => MonthPeriod::class, |
|
45
|
|
|
'months' => MonthPeriod::class, |
|
46
|
|
|
'year' => YearPeriod::class, |
|
47
|
|
|
'years' => YearPeriod::class, |
|
48
|
10 |
|
]; |
|
49
|
|
|
|
|
50
|
10 |
|
public static function fromString($string) |
|
51
|
10 |
|
{ |
|
52
|
10 |
|
if (preg_match('/^((\d+) +)?(\w+)$/', trim($string), $ms)) { |
|
53
|
|
|
if (isset(static::$periods[$ms[3]])) { |
|
54
|
10 |
|
$class = static::$periods[$ms[3]]; |
|
55
|
|
|
|
|
56
|
|
|
return new $class($ms[1] ?: 1); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
throw new FormulaSemanticsError("invalid period given: $string"); |
|
61
|
10 |
|
} |
|
62
|
|
|
|
|
63
|
10 |
|
public static function ensureValidValue($value) |
|
64
|
|
|
{ |
|
65
|
|
|
if (filter_var($value, FILTER_VALIDATE_INT) === false) { |
|
66
|
|
|
throw new FormulaSemanticsError('periodicity must be integer number'); |
|
67
|
10 |
|
} |
|
68
|
|
|
|
|
69
|
|
|
return (int) $value; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
abstract public function __toString(): string; |
|
73
|
|
|
|
|
74
|
|
|
public function toString(): string |
|
75
|
|
|
{ |
|
76
|
|
|
return $this->__toString(); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* Adds current period to the passed $startTime |
|
81
|
|
|
* |
|
82
|
|
|
* @return DateTimeImmutable time of period end |
|
83
|
|
|
*/ |
|
84
|
|
|
abstract public function addTo(DateTimeImmutable $since): DateTimeImmutable; |
|
85
|
|
|
} |
|
86
|
|
|
|