ValidJalaliDate::jalaliMonthLength()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 10
rs 10
1
<?php
2
3
namespace Milwad\LaravelValidate\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
use Illuminate\Support\Carbon;
7
8
class ValidJalaliDate implements Rule
9
{
10
    public function __construct(
11
        public string $character = '/',
12
    ) {}
13
14
    /**
15
     * Check jalali date is valid.
16
     */
17
    public function passes($attribute, $value): bool
18
    {
19
        if (! is_string($value)) {
20
            return false;
21
        }
22
23
        $date = explode($this->character, $value);
24
25
        if (count($date) <= 1) {
26
            return false;
27
        }
28
29
        return $this->checkValidDate(...$date);
0 ignored issues
show
Bug introduced by
$date of type string is incompatible with the type integer expected by parameter $year of Milwad\LaravelValidate\R...iDate::checkValidDate(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

29
        return $this->checkValidDate(/** @scrutinizer ignore-type */ ...$date);
Loading history...
30
    }
31
32
    /**
33
     * Get the validation error message.
34
     */
35
    public function message(): string
36
    {
37
        return __('validate.jalali_date');
38
    }
39
40
    /**
41
     * Checking whether the date is a Jalali date or not.
42
     */
43
    protected function checkValidDate(int $year, int $month, int $day): bool
44
    {
45
        return ($year >= -61 && $year <= 3177)
46
            && ($month >= 1 && $month <= 12)
47
            && $day >= 1 && $day <= $this->jalaliMonthLength($year, $month, $day);
48
    }
49
50
    /**
51
     * Getting the number of days through the length of the month.
52
     */
53
    protected function jalaliMonthLength(int $year, int $month, int $day): int
54
    {
55
        if (Carbon::createFromDate($year, $month, $day)->isLeapYear() && $month === 12) {
56
            return 29;
57
        }
58
        if ($month <= 6) {
59
            return 31;
60
        }
61
62
        return 30;
63
    }
64
}
65