Completed
Push — master ( 70dd79...904bc8 )
by Darius
05:35
created

ExpirationDateValidator::setYear()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
3
namespace LVR\CreditCard;
4
5
use Carbon\Carbon;
6
7
class ExpirationDateValidator
8
{
9
    /**
10
     * @var string
11
     */
12
    protected $year;
13
14
    /**
15
     * @var string
16
     */
17
    protected $month;
18
19
    /**
20
     * ExpirationDateValidator constructor.
21
     *
22
     * @param string $year
23
     * @param string $month
24
     */
25 4
    public function __construct(string $year, string $month)
26
    {
27 4
        $this->setYear($year);
28 4
        $this->month = trim($month);
29 4
    }
30
31
    /**
32
     * @param $year
33
     *
34
     * @return $this
35
     */
36
    protected function setYear($year)
37 1
    {
38
        $year = trim($year);
39 1
40
        if (strlen($year) == 2) {
41
            $year = substr(date('Y'), 0, 2) . $year;
42
        }
43
44
        $this->year = $year;
45 4
46
        return $this;
47 4
    }
48 4
49 4
    /**
50
     * @param string $year
51
     * @param string $month
52
     *
53
     * @return mixed
54
     */
55 4
    public static function validate(string $year, string $month)
56
    {
57 4
        return (new static($year, $month))->isValid();
58
    }
59
60
    /**
61
     * @return bool
62
     */
63 4
    public function isValid()
64
    {
65 4
        return $this->isValidYear()
66 4
            && $this->isValidMonth()
67
            && $this->isFeatureDate();
68
    }
69
70
    /**
71
     * @return string
72 4
     */
73
    protected function month()
74 4
    {
75 4
        return str_pad($this->month, 2, '0', STR_PAD_LEFT);
76 4
    }
77
78
    /**
79
     * @return bool
80
     */
81
    protected function isValidYear()
82 4
    {
83
        $test = '/^'.substr(date('Y'), 0, 2).'\d\d$/';
84 4
85 4
        return $this->year != ''
86
            && preg_match($test, $this->year);
87
    }
88
89
    /**
90
     * @return bool
91
     */
92
    protected function isValidMonth()
93
    {
94
        return $this->month != ''
95
            && $this->month() != '00'
96
            && preg_match('/^(0[1-9]|1[0-2])$/', $this->month());
97
    }
98
99
    /**
100
     * @return bool
101
     */
102
    protected function isFeatureDate()
103
    {
104
        return Carbon::now()->startOfDay()->lte(
105
            Carbon::createFromFormat('Y-m', $this->year.'-'.$this->month())->endOfDay()
106
        );
107
    }
108
}
109