TokenVault::hasToken()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
namespace VideoPublisher\Security;
3
4
use VideoPublisher\Exception\TokenCacheNotWritableException;
5
use VideoPublisher\Exception\TokenNotFoundException;
6
7
8
/**
9
 * Class TokenVault.
10
 *
11
 * @author Bart Malestein <[email protected]>
12
 */
13
class TokenVault
14
{
15
    /**
16
     * @var string
17
     */
18
    private $tokenCacheLocation;
19
20
    /**
21
     * TokenVault constructor.
22
     * @param $tokenCacheLocation
23
     * @throws TokenCacheNotWritableException
24
     */
25
    public function __construct($tokenCacheLocation)
26
    {
27
        $this->tokenCacheLocation = rtrim($tokenCacheLocation, '/') . '/';
28
        if (false === is_writable($tokenCacheLocation)) {
29
            throw new TokenCacheNotWritableException('token cache location isn\'t writable: ' . $tokenCacheLocation);
30
        }
31
    }
32
33
    /**
34
     * @param string $consumerKey
35
     * @param Token $token
36
     */
37
    public function addToken($consumerKey, Token $token)
38
    {
39
        file_put_contents($this->getPathForToken($consumerKey), $token->getValue());
40
    }
41
42
    /**
43
     * @param string $consumerKey
44
     */
45
    public function removeToken($consumerKey)
46
    {
47
        $location = $this->getPathForToken($consumerKey);
48
        if (file_exists($location)) {
49
            unlink($location);
50
        }
51
    }
52
53
    /**
54
     * @param string $consumerKey
55
     * @return bool
56
     */
57
    public function hasToken($consumerKey)
58
    {
59
        $location = $this->getPathForToken($consumerKey);
60
61
        return file_exists($location);
62
    }
63
64
    /**
65
     * @param string $consumerKey
66
     * @return Token
67
     * @throws TokenNotFoundException
68
     */
69
    public function getToken($consumerKey)
70
    {
71
        $location = $this->getPathForToken($consumerKey);
72
        if (false === file_exists($location)) {
73
            throw new TokenNotFoundException();
74
        }
75
        return new Token(file_get_contents($location));
76
    }
77
78
    /**
79
     * @param string $consumerKey
80
     * @return string
81
     */
82
    public function getPathForToken($consumerKey)
83
    {
84
        return $this->tokenCacheLocation . sha1($consumerKey);
85
    }
86
}