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
![]() |
|||
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 |