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

Dispensary::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
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 3
cts 3
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\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