Passed
Push — 1.x ( 672d9c...f0046e )
by Milwad
12:33
created

ValidJalaliDate::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 0
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Milwad\LaravelValidate\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
7
class ValidJalaliDate implements Rule
8
{
9
    public function __construct(
10
        public string $character = '/',
11
    ) {}
12
13
    /**
14
     * Check jalali date is valid.
15
     *
16
     * @param  string  $attribute
17
     * @param  mixed  $value
18
     * @return bool
19
     */
20
    public function passes($attribute, $value)
21
    {
22
        if (! is_string($value)) {
23
            return false;
24
        }
25
26
        $date = explode($this->character, $value);
27
28
        if (count($date) <= 1) {
29
            return false;
30
        }
31
32
        return $this->checkValidDate(...$date);
33
    }
34
35
    /**
36
     * Get the validation error message.
37
     *
38
     * @return string
39
     */
40
    public function message()
41
    {
42
        return __('validate.jalali_date');
43
    }
44
45
    /**
46
     * Checking whether the date is a Jalali date or not.
47
     */
48
    protected function checkValidDate(string $year, string $month, string $day): bool
49
    {
50
        return ($year >= -61 && $year <= 3177)
51
            && ($month >= 1 && $month <= 12)
52
            && $day >= 1 && $day <= $this->jalaliMonthLength((int) $month);
53
    }
54
55
    /**
56
     * Getting the number of days through the length of the month.
57
     */
58
    protected function jalaliMonthLength(int $month): int
59
    {
60
        if ($month <= 6) {
61
            return 31;
62
        }
63
64
        return 30; // TODO: Add 29 or 30 for some years
65
    }
66
}
67