Test Failed
Pull Request — master (#7)
by Koen
06:49
created

Dispensary   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 42
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
    public function __construct(Repository $cache, Hasher $hasher)
19
    {
20
        $this->cache = $cache;
21
        $this->hasher = $hasher;
22
    }
23
24
    public function dispense(string $cacheKey, int $ttl, int $chars): string
25
    {
26
        $token = $this->generateToken($chars);
27
28
        $this->cache->put($cacheKey, $this->hasher->make($token), $ttl);
29
30
        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
    public function verify(string $cacheKey, string $token): bool
41
    {
42
        $hashedToken = $this->cache->get($cacheKey);
43
44
        if (null === $hashedToken) {
45
            throw new TokenExpiredException();
46
        }
47
48
        return $this->hasher->check($token, $hashedToken);
49
    }
50
51
    private function generateToken(int $chars): string
52
    {
53
        return Str::random($chars);
54
    }
55
}
56