Passed
Push — master ( 8f29df...a54013 )
by Lucas
02:23
created

Client   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 159
ccs 28
cts 28
cp 1
rs 10
c 0
b 0
f 0
wmc 16

10 Methods

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