Completed
Push — master ( ab5a98...e81852 )
by keika
02:05
created

Token::getToken()   A

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
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace keika299\ConohaAPI\Common\DataStore;
4
5
6
use keika299\ConohaAPI\Conoha;
7
8
/**
9
 * Class Token
10
 *
11
 * This class manage token.
12
 *
13
 * @package keika299\ConohaAPI\Common\DataStore
14
 */
15
class Token
16
{
17
    /**
18
     * @var Conoha
19
     */
20
    private $client;
21
22
    /**
23
     * Token constructor.
24
     * @param Conoha $client
25
     */
26 55
    public function __construct(Conoha $client)
27
    {
28 55
        $this->client = $client;
29 55
    }
30
31
    /**
32
     * @return  null
33
     * @throws \Exception
34
     */
35 55
    public function initToken()
36
    {
37 55
        $token = $this->getToken();
38
39 55
        if ($token === null) {
40 1
            $cookie = new Cookies($this->client);
41 1
            if ($cookie->loadToken() !== null){
42
                $token = $cookie->loadToken();
43
            }
44
            else {
45 1
                $token = $this->generateToken();
46
            }
47 1
        }
48
49 55
        $this->setToken($token);
50 55
    }
51
52
    /**
53
     * Refresh token.
54
     *
55
     * @return null
56
     * @throws \Exception
57
     */
58 2
    public function refreshToken()
59
    {
60 2
        $newToken = $this->generateToken();
61 2
        $this->setToken($newToken);
62 2
    }
63
64
    /**
65
     * Generate token.
66
     *
67
     * @return string
68
     * @throws \Exception
69
     */
70 3
    private function generateToken()
71
    {
72 3
        $username = $this->client->getUsername();
73 3
        $password = $this->client->getUserPassword();
74
75 3
        if ($username === null || $password === null) {
76
            throw new \Exception('Cannot refresh token.');
77
        }
78
79 3
        return $this->client->identityService()->getToken()->access->token->id;
80
    }
81
82
    /**
83
     * Get token.
84
     *
85
     * @return null|string
86
     */
87 55
    public function getToken()
88
    {
89 55
        return $this->client->getToken();
90
    }
91
92
    /**
93
     * Set token.
94
     *
95
     * @param string $token
96
     * @return null
97
     */
98 55
    public function setToken($token)
99
    {
100 55
        $cookie = new Cookies($this->client);
101 55
        $cookie->saveToken($token);
102 55
        $this->client->setToken($token);
103 55
    }
104
}
105