File size: 1,411 Bytes
5f32fbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php

declare(strict_types=1);

namespace App\Actions;

use App\Jobs\SendConfirmationEmail;
use App\Models\User;

final class EmailConfirmation
{
    private function __construct(private readonly User $user) {}

    public static function forUser(User $user): self
    {
        return new self($user);
    }

    public function send(): void
    {
        if ($this->shouldSend()) {
            $this->dispatch();
        }
    }

    public function resend(): void
    {
        $this->send();
    }

    public function confirm(): void
    {
        if ($this->user->isConfirmed()) {
            return;
        }

        $this->user->update([
            'email_confirmation_code' => null,
            'email_confirmed'         => true,
            'status'                  => true,
        ]);

        $this->unlock();
    }

    private function unlock(): void
    {
        cache()->forget($this->lockKey());
    }

    private function dispatch(): void
    {
        SendConfirmationEmail::dispatch($this->user);
    }

    public function shouldSend(): bool
    {
        $key = $this->lockKey();

        if (cache()->has($key)) {
            return false;
        }

        return cache()->remember($key, now()->addHour(), function () {
            return true;
        });
    }

    private function lockKey(): string
    {
        return 'send_confirmation_email_' . $this->user->id;
    }
}