1 | <?php |
||
2 | |||
3 | namespace Ikechukwukalu\Requirepin\Rules; |
||
4 | |||
5 | use Ikechukwukalu\Requirepin\Models\OldPin; |
||
6 | use Illuminate\Contracts\Validation\Rule; |
||
7 | use Illuminate\Database\Eloquent\Collection as EloquentCollection; |
||
8 | use Illuminate\Support\Facades\Auth; |
||
9 | use Illuminate\Support\Facades\Hash; |
||
10 | |||
11 | class DisallowOldPin implements Rule |
||
12 | { |
||
13 | /** |
||
14 | * Create a new rule instance. |
||
15 | * |
||
16 | * @return void |
||
17 | */ |
||
18 | |||
19 | private int|bool $checkAll; |
||
20 | private int $number; |
||
21 | private $user; |
||
22 | |||
23 | public function __construct($checkAll = true, $number = 4) |
||
24 | { |
||
25 | // |
||
26 | $this->checkAll = $checkAll; |
||
27 | $this->number = $number; |
||
28 | |||
29 | if (is_int($this->checkAll) && !empty($this->checkAll)) { |
||
30 | $this->number = $checkAll; |
||
31 | } |
||
32 | |||
33 | $this->user = Auth::guard(config('requirepin.auth_guard', 'web'))->user(); |
||
34 | } |
||
35 | |||
36 | /** |
||
37 | * Determine if the validation rule passes. |
||
38 | * |
||
39 | * @param string $attribute |
||
40 | * @param mixed $value |
||
41 | * @return bool |
||
42 | */ |
||
43 | public function passes($attribute, $value) |
||
44 | { |
||
45 | $oldpins = $this->getOldPins(); |
||
46 | |||
47 | if ((string) $value === (string) config('requirepin.default', '0000')) |
||
48 | { |
||
49 | return false; |
||
50 | } |
||
51 | |||
52 | if ($oldpins->count() === 0) { |
||
53 | return !Hash::check($value, $this->user->pin); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
54 | } |
||
55 | |||
56 | foreach ($oldpins as $oldpin) { |
||
57 | if (Hash::check($value, $oldpin->pin)) { |
||
58 | return false; |
||
59 | } |
||
60 | } |
||
61 | |||
62 | return true; |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * Get the validation error message. |
||
67 | * |
||
68 | * @return string |
||
69 | */ |
||
70 | public function message() |
||
71 | { |
||
72 | return trans_choice('requirepin::pin.exists', |
||
73 | intval(is_int($this->checkAll)), |
||
74 | ['number' => $this->number]); |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * Get OldPin Model. |
||
79 | * |
||
80 | * @return \Illuminate\Database\Eloquent\Collection |
||
81 | */ |
||
82 | private function getOldPins(): EloquentCollection |
||
83 | { |
||
84 | if ($this->checkAll === true) { |
||
85 | return OldPin::where('user_id', $this->user->id) |
||
0 ignored issues
–
show
|
|||
86 | ->orderBy('created_at', 'desc') |
||
87 | ->get(); |
||
88 | } |
||
89 | |||
90 | return OldPin::where('user_id', $this->user->id) |
||
91 | ->orderBy('created_at', 'desc') |
||
92 | ->take($this->number) |
||
93 | ->get(); |
||
94 | } |
||
95 | } |
||
96 |