Completed
Pull Request — master (#544)
by
unknown
04:50
created

MicrosoftGraph   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 119
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 6
dl 0
loc 119
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
B parseAccessTokenResponse() 0 23 6
A getAuthorizationEndpoint() 0 4 1
A getAccessTokenEndpoint() 0 4 1
A requestAccessToken() 0 22 2
A getExtraOAuthHeaders() 0 6 1
A getAuthorizationMethod() 0 4 1
1
<?php
2
3
4
namespace OAuth\OAuth2\Service;
5
use OAuth\Common\Consumer\CredentialsInterface;
6
use OAuth\Common\Http\Client\ClientInterface;
7
use OAuth\Common\Http\Exception\TokenResponseException;
8
use OAuth\Common\Http\Uri\Uri;
9
use OAuth\Common\Http\Uri\UriInterface;
10
use OAuth\Common\Storage\TokenStorageInterface;
11
use OAuth\Common\Token\TokenInterface;
12
use OAuth\OAuth2\Token\StdOAuth2Token;
13
14
/**
15
 * Class Azure
16
 * @package OAuth\OAuth2\Service
17
 * @author Juan Diaz - FuriosoJack <[email protected]>
18
 */
19
class MicrosoftGraph extends AbstractService
20
{
21
    private $resources = array(
22
        'graph' => 'https://graph.windows.net/'
23
    );
24
    public function __construct(CredentialsInterface $credentials, ClientInterface $httpClient, TokenStorageInterface $storage, array $scopes = array(), UriInterface $baseApiUri = null, $stateParameterInAutUrl = false, $apiVersion = "")
25
    {
26
        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri, $stateParameterInAutUrl, $apiVersion);
27
        if(is_null($baseApiUri)){
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
28
            $this->baseApiUri = new Uri($this->resources['graph'].'myorganization/');
29
        }
30
    }
31
32
    /**
33
     * Parses the access token response and returns a TokenInterface.
34
     *
35
     *
36
     * @param string $responseBody
37
     *
38
     * @return TokenInterface
39
     *
40
     * @throws TokenResponseException
41
     */
42
    protected function parseAccessTokenResponse($responseBody)
43
    {
44
        $data = json_decode($responseBody, true);
45
        if (null === $data || !is_array($data)) {
46
            throw new TokenResponseException('Unable to parse response.');
47
        } elseif (isset($data['error_description'])) {
48
            throw new TokenResponseException('Error in retrieving token: "' . $data['error_description'] . '"');
49
        } elseif (isset($data['error'])) {
50
            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
51
        }
52
53
        $token = new StdOAuth2Token();
54
        $token->setAccessToken($data['access_token']);
55
        $token->setLifeTime($data['expires_in']);
56
        if (isset($data['refresh_token'])) {
57
            $token->setRefreshToken($data['refresh_token']);
58
            unset($data['refresh_token']);
59
        }
60
        unset($data['access_token']);
61
        unset($data['expires_in']);
62
        $token->setExtraParams($data);
63
        return $token;
64
    }
65
66
    /**
67
     * Returns the authorization API endpoint.
68
     *
69
     * @return UriInterface
70
     */
71
    public function getAuthorizationEndpoint()
72
    {
73
        return new Uri('https://login.microsoftonline.com/common/oauth2/authorize');
74
    }
75
76
    /**
77
     * Returns the access token API endpoint.
78
     *
79
     * @return UriInterface
80
     */
81
    public function getAccessTokenEndpoint()
82
    {
83
        return new Uri('https://login.microsoftonline.com/common/oauth2/token');
84
    }
85
86
    /**
87
     * @param $code
88
     * @param null $state
89
     * @return TokenInterface
90
     * @throws Exception\InvalidAuthorizationStateException
91
     * @throws TokenResponseException
92
     */
93
    public function requestAccessToken($code, $state = null)
94
    {
95
        if (null !== $state) {
96
            $this->validateAuthorizationState($state);
97
        }
98
        $bodyParams = array(
99
            'code'          => $code,
100
            'client_id'     => $this->credentials->getConsumerId(),
101
            'client_secret' => $this->credentials->getConsumerSecret(),
102
            'redirect_uri'  => $this->credentials->getCallbackUrl(),
103
            'grant_type'    => 'authorization_code',
104
            'resource' => $this->resources['graph']
105
        );
106
        $responseBody = $this->httpClient->retrieveResponse(
107
            $this->getAccessTokenEndpoint(),
108
            $bodyParams,
109
            $this->getExtraOAuthHeaders()
110
        );
111
        $token = $this->parseAccessTokenResponse($responseBody);
112
        $this->storage->storeAccessToken($this->service(), $token);
113
        return $token;
114
    }
115
116
    /**
117
     * Devuelve los heades que tendra obtener el AccessToken
118
     * @return array
119
     */
120
    protected function getExtraOAuthHeaders()
121
    {
122
        return array(
123
            'Content-Type'=>'application/x-www-form-urlencoded'
124
        );
125
    }
126
127
    /**
128
     * Returns a class constant from ServiceInterface define el metodo e autorizacion del API
129
     * Header is the sane default.
130
     *
131
     * @return int
132
     */
133
    protected function getAuthorizationMethod()
134
    {
135
        return static::AUTHORIZATION_METHOD_HEADER_BEARER;
136
    }
137
}