TokenManager::isAccessTokenExpired()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 4
nc 2
nop 0
1
<?php namespace OutlookRestClient\Facade;
2
/**
3
 * Copyright 2017 OpenStack Foundation
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 * http://www.apache.org/licenses/LICENSE-2.0
8
 * Unless required by applicable law or agreed to in writing, software
9
 * distributed under the License is distributed on an "AS IS" BASIS,
10
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
 * See the License for the specific language governing permissions and
12
 * limitations under the License.
13
 **/
14
15
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
16
use Symfony\Component\Console\Exception\LogicException;
17
18
/**
19
 * Class TokenManager
20
 * @package OutlookRestClient\Facade
21
 */
22
final class TokenManager implements ITokenManager
23
{
24
    /**
25
     * @var array
26
     */
27
    private $access_token = null;
28
29
    /**
30
     * @var callable
31
     */
32
    private $token_callback;
33
34
    /**
35
     * @param array $access_token
36
     */
37
    public function storeToken(array $access_token){
38
        $this->access_token = $access_token;
39
    }
40
41
    public function clearToken(){
42
        $this->access_token = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $access_token.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
43
    }
44
45
    /**
46
     * @return bool
47
     */
48
    public function isAccessTokenExpired(){
49
        if(is_null($this->access_token) || !isset($this->access_token['expires'])) return true;
50
        // Check if token is expired
51
        //Get current time + 5 minutes (to allow for time differences)
52
        $now   = time() + ITokenManager::TimeSkew;
53
        return $this->access_token['expires'] <= $now ;
54
    }
55
56
    /**
57
     * @param null|string $refresh_token
58
     * @return array|null
59
     * @throws LogicException
60
     */
61
    public function fetchAccessTokenWithRefreshToken($refresh_token = null){
62
        // Token is expired (or very close to it)
63
        // so let's refresh
64
        if(empty($refresh_token) && !is_null($this->access_token) && isset($this->access_token['refresh_token']));
65
            $refresh_token =  $this->access_token['refresh_token'];
66
67
        if (empty($refresh_token)) {
68
            throw new LogicException(
69
                'refresh token is null'
70
            );
71
        }
72
        // Initialize the OAuth client
73
        $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
74
            'clientId'                => getenv('OUTLOOK_OAUTH_APP_ID'),
75
            'clientSecret'            => getenv('OUTLOOK_OAUTH_APP_PASSWORD'),
76
            'urlAuthorize'            => getenv('OUTLOOK_OAUTH_AUTHORITY').getenv('OUTLOOK_OAUTH_AUTHORIZE_ENDPOINT'),
77
            'urlAccessToken'          => getenv('OUTLOOK_OAUTH_AUTHORITY').getenv('OUTLOOK_OAUTH_TOKEN_ENDPOINT'),
78
            'urlResourceOwnerDetails' => '',
79
            'scopes'                  => getenv('OUTLOOK_OAUTH_SCOPES')
80
        ]);
81
82
        try {
83
            $new_token = $oauthClient->getAccessToken('refresh_token', [
84
                'refresh_token' =>$refresh_token
85
            ]);
86
87
            $new_token = $new_token->jsonSerialize();
88
            // Store the new values
89
            $this->storeToken($new_token);
90
            if ($this->token_callback) {
91
                call_user_func($this->token_callback, $new_token);
92
            }
93
            return $new_token;
94
        }
95
        catch (IdentityProviderException $e) {
96
            $this->clearToken();
97
            return null;
98
        }
99
    }
100
101
    /**
102
     * @return array
103
     */
104
    public function getAccessToken() {
105
106
        if(is_null($this->access_token)) return null;
107
108
        if ($this->isAccessTokenExpired()) {
109
           $this->fetchAccessTokenWithRefreshToken();
110
        }
111
112
        // Token is still valid, just return it
113
        return $this->access_token;
114
115
    }
116
117
    /**
118
     * sets function to be called when an access token is fetched
119
     * @param callable $token_callback
120
     * @return void
121
     */
122
    public function setTokenCallback(callable $token_callback){
123
        $this->token_callback = $token_callback;
124
    }
125
}