Passed
Pull Request — master (#7)
by Koen
04:12
created

Dispensary   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 42
ccs 15
cts 15
cp 1
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A dispense() 0 7 1
A __construct() 0 4 1
A generateToken() 0 3 1
A verify() 0 9 2
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\Cache\Repository;
9
use Illuminate\Contracts\Hashing\Hasher;
10
use Illuminate\Support\Str;
11
12
final class Dispensary
13
{
14
    private Repository $cache;
15
16
    private Hasher $hasher;
17
18 17
    public function __construct(Repository $cache, Hasher $hasher)
19
    {
20 17
        $this->cache = $cache;
21 17
        $this->hasher = $hasher;
22 17
    }
23
24 9
    public function dispense(string $cacheKey, int $ttl, int $chars): string
25
    {
26 9
        $token = $this->generateToken($chars);
27
28 9
        $this->cache->put($cacheKey, $this->hasher->make($token), $ttl);
29
30 9
        return $token;
31
    }
32
33
    /**
34
     * @param  string $cacheKey
35
     * @param  string $token
36
     * @return bool
37
     * @throws \App\Auth\Dispensary\Exceptions\TokenExpiredException
38
     * @throws \Psr\SimpleCache\InvalidArgumentException
39
     */
40 7
    public function verify(string $cacheKey, string $token): bool
41
    {
42 7
        $hashedToken = $this->cache->get($cacheKey);
43
44 7
        if (null === $hashedToken) {
45 2
            throw new TokenExpiredException();
46
        }
47
48 5
        return $this->hasher->check($token, $hashedToken);
49
    }
50
51 9
    private function generateToken(int $chars): string
52
    {
53 9
        return Str::random($chars);
54
    }
55
}
56