Dispensary::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Auth\Dispensary;
6
7
use App\Auth\Dispensary\Exceptions\TokenExpiredException;
8
use Illuminate\Contracts\Hashing\Hasher;
9
use Illuminate\Support\Str;
10
11
final class Dispensary
12
{
13
    private Repository $repository;
14
15
    private Hasher $hasher;
16
17
    public function __construct(Repository $repository, Hasher $hasher)
18 17
    {
19
        $this->repository = $repository;
20 17
        $this->hasher = $hasher;
21 17
    }
22 17
23
    public function dispense(string $key, int $ttl, int $chars): string
24 9
    {
25
        $token = $this->generateToken($chars);
26 9
27
        $this->repository->put($key, $this->hasher->make($token), $ttl);
28 9
29
        return $token;
30 9
    }
31
32
    /**
33
     * @param  string $key
34
     * @param  string $token
35
     * @return bool
36
     * @throws \App\Auth\Dispensary\Exceptions\TokenExpiredException
37
     */
38
    public function verify(string $key, string $token): bool
39
    {
40 7
        $hashedToken = $this->repository->get($key);
41
42 7
        if (null === $hashedToken) {
43
            throw new TokenExpiredException();
44 7
        }
45 2
46
        return $this->hasher->check($token, $hashedToken);
47
    }
48 5
49
    private function generateToken(int $chars): string
50
    {
51 9
        return Str::random($chars);
52
    }
53
}
54