Passed
Push — master ( a54013...97291e )
by Lucas
02:35
created

Client::getToken()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 4
nc 6
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 4
rs 9.2
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\OAuth2\Client\Provider\MercadoLibreResourceOwner;
18
use League\OAuth2\Client\Token\AccessToken;
19
20
/**
21
 * Client class
22
 *
23
 * An easy-to-use client to access the MercadoLibre API services.
24
 *
25
 * To use this client, must first register the application in
26
 * {@link http://applications.mercadolibre.com/ MercadoLibre},
27
 * since the API must grant the clientId and clientSecret values.
28
 * The options required for the constructor are:
29
 *
30
 * - authSite
31
 * - clientId
32
 * - clientSecret
33
 * - redirectUri
34
 *
35
 * Optionally, can initialize the client with a previously
36
 * generated token, passing it with the `token` key.
37
 *
38
 * @example
39
 * <pre>
40
 * $client = new \Docta\MercadoLibre\Client([
41
 *     'authSite'     => '{mercadolibre-auth-site}',
42
 *     'clientId'     => '{mercadolibre-client-id}',
43
 *     'clientSecret' => '{mercadolibre-client-secret}',
44
 *     'redirectUri'  => 'https://example.com/oauth/'
45
 * ]);
46
 *
47
 * if (!isset($_GET['code'])) {
48
 *     $authUrl = $provider->getAuthUrl();
49
 *     $_SESSION['state'] = $provider->getState();
50
 *     header('Location: ' . $authUrl);
51
 *     exit;
52
 * } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['state'])) {
53
 *     unset($_SESSION['state']);
54
 *     exit('Invalid state');
55
 * } else {
56
 *     try {
57
 *         $token = $client->getToken($_GET['code']);
58
 *         $owner = $client->getOwner();
59
 *         $items = $client->post('/items');
60
 *     } catch (Exception $e) {
61
 *         exit($e->getMessage());
62
 *     }
63
 * }
64
 * </pre>
65
 */
66
class Client extends ClientBase
67
{
68
    /**
69
     * Builds and return the authorization URL
70
     *
71
     * The url returned by this method depends on the `authSite` option passed
72
     * to the constructor. For example, if the option set is `MLA`, it will
73
     * return `https://auth.mercadolibre.com.ar/authorization`.
74
     *
75
     * In addition, the url will contain the following query parameters:
76
     *
77
     * - `response_type`
78
     * - `client_id`
79
     * - `redirect_uri`
80
     * - `state`
81
     *
82
     * @return string The authorization URL
83
     */
84 2
    public function getAuthUrl()
85
    {
86 2
        return $this->provider->getAuthorizationUrl();
87
    }
88
89
    /**
90
     * Returns the current value of the state parameter
91
     *
92
     * When the authorization url is generated, this includes the parameter
93
     * `state`. This method get its value to store in a session and then be
94
     * able to compare when the server redirects back to the application.
95
     * The objective of this parameter is to mitigate CSRF attacks.
96
     *
97
     * @link https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) Cross-Site Request Forgery (CSRF)
98
     *
99
     * @return string The current value of the state parameter
100
     */
101 2
    public function getState()
102
    {
103 2
        return $this->provider->getState();
104
    }
105
106
    /**
107
     * Get a token
108
     *
109
     * If a string is passed, this method assumes that
110
     * it is a code that must be exchanged for a token.
111
     *
112
     * If a valid token is passed, it returns the same token;
113
     * but if the token has expired and has a refresh token,
114
     * then it requests and returns a new token.
115
     *
116
     * In all cases that a token returns, it is established as
117
     * the default token. In any other case it returns null.
118
     *
119
     * @param AccessToken|string|null $token Code or token
120
     * @return AccessToken The {@link https://goo.gl/QEoCNV access token}
121
     */
122 10
    public function getToken($token = null)
123
    {
124 10
        $this->setToken($token);
125
126 10
        return $this->token && $this->token->getRefreshToken() && $this->token->hasExpired()
127 1
            ? $this->refresh($this->token)
128 10
            : $this->token;
129
    }
130
131
    /**
132
     * Set a token
133
     *
134
     * Set the token passed as the default token. A default token can
135
     * also be set using the `token` key in the constructor options.
136
     *
137
     * @param AccessToken|string $token Code or token
138
     * @return AccessToken The {@link https://goo.gl/QEoCNV access token}
139
     */
140 12
    public function setToken($token)
141
    {
142 12
        if (is_string($token)) {
143 11
            return $this->authorize($token);
144 12
        } elseif ($token instanceof AccessToken) {
0 ignored issues
show
introduced by
$token is always a sub-type of League\OAuth2\Client\Token\AccessToken.
Loading history...
145 12
            return ($this->token = $token);
146
        }
147 9
    }
148
149
    /**
150
     * Make a GET request to API services
151
     *
152
     * @param string $path Path relative to the API url
153
     * @param array $query Optional: query parameters
154
     * @return array The response of API services
155
     */
156 1
    public function get($path, array $query = [])
157
    {
158 1
        return $this->getResponse('GET', $path, $query);
159
    }
160
161
    /**
162
     * Make a POST request to API services
163
     *
164
     * @param string $path Path relative to the API url
165
     * @param array $data Optional: data to be sent to the API services
166
     * @param array $query Optional: query parameters
167
     * @return array The response of API services
168
     */
169 1
    public function post($path, array $data = [], array $query = [])
170
    {
171 1
        return $this->getResponse('POST', $path, $query, $data);
172
    }
173
174
    /**
175
     * Make a PUT request to API services
176
     *
177
     * @param string $path Path relative to the API url
178
     * @param array $data Optional: data to be sent to the API services
179
     * @param array $query Optional: query parameters
180
     * @return array The response of API services
181
     */
182 1
    public function put($path, array $data = [], array $query = [])
183
    {
184 1
        return $this->getResponse('PUT', $path, $query, $data);
185
    }
186
187
    /**
188
     * Make a DELETE request to API services
189
     *
190
     * @param string $path Path relative to the API url
191
     * @param array $query Optional: query parameters
192
     * @return array The response of API services
193
     */
194 1
    public function delete($path, array $query = [])
195
    {
196 1
        return $this->getResponse('DELETE', $path, $query);
197
    }
198
199
    /**
200
     * Make a OPTIONS request to API services
201
     *
202
     * @param string $path Path relative to the API url
203
     * @param array $query Optional: query parameters
204
     * @return array The response of API services
205
     */
206 1
    public function options($path, array $query = [])
207
    {
208 1
        return $this->getResponse('OPTIONS', $path, $query);
209
    }
210
211
    /**
212
     * Gets data about the owner of the resources.
213
     *
214
     * @return MercadoLibreResourceOwner The {@link https://goo.gl/bBmFoP owner data}
215
     */
216 1
    public function getOwner()
217
    {
218 1
        return $this->token ? $this->provider->getResourceOwner($this->token) : null;
219
    }
220
}
221