Date::ensureValidValue()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.0208

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 6
nop 1
dl 0
loc 23
ccs 11
cts 12
cp 0.9167
crap 6.0208
rs 9.2222
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-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
 * Date addon.
19
 *
20
 * @author Andrii Vasyliev <[email protected]>
21
 */
22
abstract class Date implements AddonInterface
23
{
24
    /**
25
     * @var DateTimeImmutable
26
     */
27
    protected $value;
28
29 15
    public function __construct($value)
30
    {
31 15
        $this->value = static::ensureValidValue($value);
32 15
    }
33
34 11
    public function getValue()
35
    {
36 11
        return $this->value;
37
    }
38
39 16
    public static function ensureValidValue($value)
40
    {
41 16
        if ($value instanceof DateTimeImmutable) {
42 13
            return $value;
43
        }
44
45 7
        if (preg_match('/^(\d{4})-(\d{2})$/', $value, $ms)) {
46 5
            return new DateTimeImmutable("$ms[1]-$ms[2]-01");
47
        }
48
49 3
        if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value, $ms)) {
50 3
            return new DateTimeImmutable("$ms[1]-$ms[2]-$ms[3]");
51
        }
52
53 1
        if (preg_match('/^(\d{2})\.(\d{4})$/', $value, $ms)) {
54 1
            return new DateTimeImmutable("$ms[2]-$ms[1]-01");
55
        }
56
57 1
        if (preg_match('/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/', $value, $ms)) {
58 1
            return new DateTimeImmutable("$ms[3]-$ms[2]-$ms[1]");
59
        }
60
61
        throw new FormulaSemanticsError('invalid date given');
62
    }
63
}
64