Completed
Push — master ( 904bc8...6e1df5 )
by Darius
06:40 queued 05:27
created

ExpirationDateValidator::isValidMonth()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

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