Passed
Push — master ( e3ed84...3f53d8 )
by Dominic
02:49
created

TokenManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

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
rs 10
1
<?php
2
3
namespace tbclla\Revolut\Auth;
4
5
use tbclla\Revolut\Auth\Requests\AccessTokenRequest;
6
use tbclla\Revolut\Exceptions\AppUnauthorizedException;
7
use tbclla\Revolut\Interfaces\GrantsAccessTokens;
8
use tbclla\Revolut\Repositories\TokenRepository;
9
10
class TokenManager
11
{
12
	/**
13
	 * The token repository
14
	 *
15
	 * @var \tbclla\Revolut\Repositories\TokenRepository
16
	 */
17
	private $tokenRepository;
18
19
	/**
20
	 * The access token request
21
	 *
22
	 * @var \tbclla\Revolut\Auth\Requests\AccessTokenRequest
23
	 */
24
	private $accessTokenRequest;
25
26
	/**
27
	 * Create a token manager
28
	 *
29
	 * @param \tbclla\Revolut\Repositories\TokenRepository $tokenRepository
30
	 * @param \tbclla\Revolut\Auth\Requests\AccessTokenRequest $accessTokenRequest
31
	 * @return void
32
	 */
33
	public function __construct(TokenRepository $tokenRepository, AccessTokenRequest $accessTokenRequest)
34
	{
35
		$this->tokenRepository = $tokenRepository;
36
		$this->accessTokenRequest = $accessTokenRequest;
37
	}
38
39
	/**
40
	 * Get an access token from the repository,
41
	 * or request a new access token
42
	 *
43
	 * @return \tbclla\Revolut\Auth\AccessToken
44
	 */
45
	public function getAccessToken()
46
	{
47
		$accessToken = $this->tokenRepository->getAccessToken();
48
49
		return $accessToken ?? $this->refreshAccessToken();
50
	}
51
52
	/**
53
	 * Get a refresh token from the repository
54
	 *
55
	 * @return \tbclla\Revolut\Auth\RefreshToken|null
56
	 */
57
	public function getRefreshToken()
58
	{
59
		return $this->tokenRepository->getRefreshToken();
60
	}
61
62
	/**
63
	 * Exchange a refresh token for a new access token
64
	 *
65
	 * @return \tbclla\Revolut\Auth\AccessToken
66
	 * @throws \tbclla\Revolut\Exceptions\AppUnauthorizedException
67
	 */
68
	public function refreshAccessToken()
69
	{
70
		if (!$refreshToken = $this->getRefreshToken()) {
71
			throw new AppUnauthorizedException('No refresh token found. Re-authorization required.');
72
		}
73
74
		return $this->requestAccessToken($refreshToken);
75
	}
76
77
	/**
78
	 * Request a new access token
79
	 *
80
	 * @param \tbclla\Revolut\Interfaces\GrantsAccessTokens $token
81
	 * @return \tbclla\Revolut\Auth\AccessToken
82
	 */
83
	public function requestAccessToken(GrantsAccessTokens $token)
84
	{
85
		$response = $this->accessTokenRequest->exchange($token);
86
87
		if (isset($response['refresh_token'])) {
88
			$this->tokenRepository->createRefreshToken($response['refresh_token']);
89
		}
90
91
		return $this->tokenRepository->createAccessToken($response['access_token']);
92
	}
93
}
94