Client::getAuthorizationUrl()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * MercadoLibre PHP SDK
4
 *
5
 * Licensed under The MIT License
6
 * For full copyright and license information, please see the LICENSE file
7
 * Redistributions of files must retain the above copyright notice.
8
 *
9
 * @copyright 2018 Lucas Banegas <[email protected]>
10
 * @license https://opensource.org/licenses/MIT MIT License
11
 * @author Lucas Banegas <[email protected]>
12
 * @link https://github.com/docta/mercadolibre Repository
13
 * @link https://docta.github.io/mercadolibre Documentation
14
 */
15
namespace Docta\MercadoLibre;
16
17
use Docta\MercadoLibre\Exception\ClientException;
18
use Docta\MercadoLibre\OAuth2\Client\Provider;
19
use Docta\MercadoLibre\OAuth2\Client\ResourceGeneric;
20
use Docta\MercadoLibre\OAuth2\Client\ResourceOwner;
21
use InvalidArgumentException;
22
use League\OAuth2\Client\Provider\AbstractProvider;
23
use League\OAuth2\Client\Token\AccessToken;
24
use Psr\Http\Message\RequestInterface;
25
use Psr\Http\Message\ResponseInterface;
26
27
/**
28
 * Represents a simplified version of MercadoLibre Provider.
29
 */
30
class Client extends Provider
31
{
32
    /**
33
     * @var AccessToken
34
     */
35
    protected $token;
36
37
    /**
38
     * @var ResourceOwner
39
     */
40
    protected $owner;
41
42
    /**
43
     * Constructor.
44
     *
45
     * @param string $authSite The site where the application was registered (ex: `MLA`)
46
     * @param string $clientId The App ID granted by MercadoLibre
47
     * @param string $clientSecret The secret key granted by MercadoLibre
48
     * @param string $redirectUri The URI that will process the MercadoLibre callback
49
     * @param AccessToken|string $token Code or token previously granted (optional)
50
     * @throws InvalidArgumentException
51
     * @throws ClientException
52
     */
53 17
    public function __construct(
54
        $authSite,
55
        $clientId,
56
        $clientSecret,
57
        $redirectUri,
58
        $token = null
59
    ) {
60 17
        parent::__construct(compact(
61 17
            'authSite',
62 17
            'clientId',
63 17
            'clientSecret',
64 17
            'redirectUri'
65
        ));
66
67 17
        if ($token) {
68 1
            $this->setToken($token);
69
        }
70 17
    }
71
72
    /**
73
     * Builds and returns the authorization URL.
74
     *
75
     * @param array $options
76
     * @return string Authorization URL
77
     */
78 1
    public function getAuthorizationUrl(array $options = [])
79
    {
80 1
        return parent::getAuthorizationUrl($options);
81
    }
82
83
    /**
84
     * Returns the current value of the state parameter.
85
     *
86
     * @return string
87
     */
88 1
    public function getState()
89
    {
90 1
        return parent::getState();
91
    }
92
93
    /**
94
     * Set a token using a code or a previously created token.
95
     *
96
     * @param AccessToken|string $token Code or token previously granted
97
     * @throws ClientException
98
     * @return AccessToken|null
99
     */
100 11
    public function setToken($token)
101
    {
102 11
        $this->token = $token instanceof AccessToken
103 11
            ? $token : $this->getAccessToken('authorization_code', ['code' => $token]);
104
105 7
        return $this->getToken();
106
    }
107
108
    /**
109
     * Get the current token.
110
     *
111
     * @throws ClientException
112
     * @return AccessToken|null
113
     */
114 11
    public function getToken()
115
    {
116 11
        if ($this->token && $this->token->hasExpired() && $this->token->getRefreshToken()) {
117 1
            $options = ['refresh_token' => $this->token->getRefreshToken()];
118 1
            $this->token = $this->getAccessToken('refresh_token', $options);
119
        }
120
121 11
        return $this->token;
122
    }
123
124
    /**
125
     * Get the owner resource for the current token.
126
     *
127
     * @throws ClientException
128
     * @return ResourceOwner|null
129
     */
130 2
    public function getOwner()
131
    {
132 2
        if ($this->getToken()) {
133 1
            $this->owner = $this->getResourceOwner($this->getToken());
134
        }
135
136 2
        return $this->owner;
137
    }
138
139
    /**
140
     * Execute a GET request
141
     *
142
     * @param string $path Path relative to the API URL
143
     * @param array $query Query parameters to include in the URL (optional)
144
     * @throws ClientException
145
     * @return ResourceGeneric The resource obtained by the request
146
     */
147 1
    public function get($path, array $query = [])
148
    {
149 1
        return $this->execute('GET', $path, $query);
150
    }
151
152
    /**
153
     * Execute a POST request
154
     *
155
     * @param string $path Path relative to the API URL
156
     * @param array $data Data to be sent through the HTTP headers (optional)
157
     * @param array $query Query parameters to include in the URL (optional)
158
     * @throws ClientException
159
     * @return ResourceGeneric The resource obtained by the request
160
     */
161 1
    public function post($path, array $data = [], array $query = [])
162
    {
163 1
        return $this->execute('POST', $path, $query, $data);
164
    }
165
166
    /**
167
     * Execute a PUT request
168
     *
169
     * @param string $path Path relative to the API URL
170
     * @param array $data Data to be sent through the HTTP headers (optional)
171
     * @param array $query Query parameters to include in the URL (optional)
172
     * @throws ClientException
173
     * @return ResourceGeneric The resource obtained by the request
174
     */
175 1
    public function put($path, array $data = [], array $query = [])
176
    {
177 1
        return $this->execute('PUT', $path, $query, $data);
178
    }
179
180
    /**
181
     * Execute a DELETE request
182
     *
183
     * @param string $path Path relative to the API URL
184
     * @param array $query Query parameters to include in the URL (optional)
185
     * @throws ClientException
186
     * @return ResourceGeneric The resource obtained by the request
187
     */
188 1
    public function delete($path, array $query = [])
189
    {
190 1
        return $this->execute('DELETE', $path, $query);
191
    }
192
193
    /**
194
     * Execute a OPTIONS request
195
     *
196
     * @param string $path Path relative to the API URL
197
     * @param array $query Query parameters to include in the URL (optional)
198
     * @throws ClientException
199
     * @return ResourceGeneric The resource obtained by the request
200
     */
201 1
    public function options($path, array $query = [])
202
    {
203 1
        return $this->execute('OPTIONS', $path, $query);
204
    }
205
206
    /**
207
     * Execute a custom request
208
     *
209
     * @param string $method Request method
210
     * @param string $path Path relative to the API URL
211
     * @param array $query Query parameters to include in the URL (optional)
212
     * @param array $data Data to be sent through the HTTP headers (optional)
213
     * @throws ClientException
214
     * @return ResourceGeneric The resource obtained by the request
215
     */
216 1
    public function execute($method, $path, array $query = [], array $data = [])
217
    {
218 1
        $url = $this->getApiUrl($path, $query);
219 1
        $request = $this->buildRequest($method, $url, $data);
220 1
        $response = $this->getParsedResponse($request);
221 1
        return $this->buildResource($response);
222
    }
223
224
    /**
225
     * Build and return an appropriate request.
226
     *
227
     * @param string $method
228
     * @param string $url
229
     * @param array $data
230
     * @return RequestInterface
231
     */
232 3
    public function buildRequest($method, $url, array $data = [])
233
    {
234 3
        $options = empty($data) ? $data : [
235 2
            'headers' => ['content-type' => 'application/json'],
236 3
            'body' => json_encode($data)
237
        ];
238
239 3
        return empty($this->getToken())
240 2
            ? $this->getRequest($method, $url, $options)
241 3
            : $this->getAuthenticatedRequest($method, $url, $this->getToken(), $options);
242
    }
243
244
    /**
245
     * Build and return a resource.
246
     *
247
     * @param mixed $response
248
     * @return ResourceGeneric|mixed
249
     */
250 2
    public function buildResource($response = null)
251
    {
252 2
        return is_array($response) ? new ResourceGeneric($response) : $response;
253
    }
254
255
    /**
256
     * Checks a provider response for errors.
257
     *
258
     * @throws ClientException
259
     * @param ResponseInterface $response
260
     * @param array|string $data Parsed response data
261
     * @return void
262
     */
263 12
    protected function checkResponse(ResponseInterface $response, $data)
264
    {
265 12
        if (isset($data['error'])) {
266 4
            throw new ClientException((string) $data['error'], (int) $data['status'], $data);
267
        }
268 8
    }
269
}
270