Passed
Push — master ( 97291e...d6c6a3 )
by Lucas
07:03
created

Client::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 5
dl 0
loc 16
ccs 8
cts 8
cp 1
crap 2
rs 9.4285
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\OAuth2\Client\Provider;
18
use Docta\MercadoLibre\OAuth2\Client\ResourceGeneric;
19
use League\OAuth2\Client\Provider\AbstractProvider;
20
use League\OAuth2\Client\Token\AccessToken;
21
use Psr\Http\Message\RequestInterface;
22
use Psr\Http\Message\ResponseInterface;
23
24
/**
25
 * Represents a simplified version of MercadoLibre Provider.
26
 */
27
class Client extends Provider
28
{
29
    /**
30
     * @var AccessToken Token
31
     */
32
    protected $token;
33
34
    /**
35
     * Constructor.
36
     *
37
     * @param string $authSite The site where the application was registered (ex: `MLA`)
38
     * @param string $clientId The App ID granted by MercadoLibre
39
     * @param string $clientSecret The secret key granted by MercadoLibre
40
     * @param string $redirectUri The URI that will process the MercadoLibre callback
41
     * @param AccessToken|string $token A code or token previously created (optional)
42
     */
43 18
    public function __construct(
44
        $authSite,
45
        $clientId,
46
        $clientSecret,
47
        $redirectUri,
48
        $token = null
49
    ) {
50 18
        parent::__construct(compact(
51 18
            'authSite',
52 18
            'clientId',
53 18
            'clientSecret',
54 18
            'redirectUri'
55
        ));
56
57 18
        if ($token) {
58 18
            $this->setToken($token);
59
        }
60 18
    }
61
62
    /**
63
     * Setter.
64
     *
65
     * @internal
66
     * @param string The inaccessible property name
0 ignored issues
show
Bug introduced by
The type Docta\MercadoLibre\The was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
67
     * @param mixed $value The value for the inaccessible property
68
     */
69 2
    public function __set($name, $value)
70
    {
71 2
        if ($name === 'token') {
72 2
            $this->setToken($value);
73
        }
74 2
    }
75
76
    /**
77
     * Getter.
78
     *
79
     * @internal
80
     * @param string $name The inaccessible property name
81
     * @return mixed The inaccessible property value
82
     */
83 4
    public function __get($name)
84
    {
85 4
        return $name === 'token'
86 4
            ? $this->getToken()
87 4
            : $this->{$name};
88
    }
89
90
    /**
91
     * Build and return the authorization URL, but if set `redirect`
92
     * to `true`, redirects the client for authorization.
93
     *
94
     * @see AbstractProvider::authorize()
95
     * @see AbstractProvider::getAuthorizationUrl()
96
     *
97
     * @param boolean $redirect
98
     * @return string The authorization url
99
     */
100 1
    public function getAuthorizationUrl($redirect = false)
101
    {
102 1
        return $redirect === true
103
            ? parent::authorize()
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::authorize() targeting League\OAuth2\Client\Pro...ctProvider::authorize() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
104 1
            : parent::getAuthorizationUrl();
105
    }
106
107
    /**
108
     * Set a token using a code or a previously created token.
109
     *
110
     * @param AccessToken|string $token Token or code
111
     * @return AccessToken|null The token
112
     */
113 18
    public function setToken($token)
114
    {
115 18
        if (is_string($token)) {
116 2
            $this->token = $this->getAccessToken('authorization_code', ['code' => $token]);
117 18
        } elseif ($token instanceof AccessToken) {
0 ignored issues
show
introduced by
$token is always a sub-type of League\OAuth2\Client\Token\AccessToken.
Loading history...
118 18
            $this->token = $token;
119
        }
120
121 18
        return $this->getToken();
122
    }
123
124
    /**
125
     * Get the current token and if it exists and is expired try refreshing.
126
     *
127
     * @return AccessToken|null The token
128
     */
129 18
    public function getToken()
130
    {
131 18
        if ($this->token && $this->token->hasExpired() && $this->token->getRefreshToken()) {
132 1
            $this->token = $this->getAccessToken('refresh_token', [
133 1
                'refresh_token' => $this->token->getRefreshToken()
134
            ]);
135
        }
136
137 18
        return $this->token;
138
    }
139
140
    /**
141
     * Execute a GET request
142
     *
143
     * @param string $path Path relative to the API URL
144
     * @param array $query Query parameters to include in the URL (optional)
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
     * @return ResourceGeneric The resource obtained by the request
159
     */
160 1
    public function post($path, array $data = [], array $query = [])
161
    {
162 1
        return $this->execute('POST', $path, $query, $data);
163
    }
164
165
    /**
166
     * Execute a PUT request
167
     *
168
     * @param string $path Path relative to the API URL
169
     * @param array $data Data to be sent through the HTTP headers (optional)
170
     * @param array $query Query parameters to include in the URL (optional)
171
     * @return ResourceGeneric The resource obtained by the request
172
     */
173 1
    public function put($path, array $data = [], array $query = [])
174
    {
175 1
        return $this->execute('PUT', $path, $query, $data);
176
    }
177
178
    /**
179
     * Execute a DELETE request
180
     *
181
     * @param string $path Path relative to the API URL
182
     * @param array $query Query parameters to include in the URL (optional)
183
     * @return ResourceGeneric The resource obtained by the request
184
     */
185 1
    public function delete($path, array $query = [])
186
    {
187 1
        return $this->execute('DELETE', $path, $query);
188
    }
189
190
    /**
191
     * Execute a OPTIONS request
192
     *
193
     * @param string $path Path relative to the API URL
194
     * @param array $query Query parameters to include in the URL (optional)
195
     * @return ResourceGeneric The resource obtained by the request
196
     */
197 1
    public function options($path, array $query = [])
198
    {
199 1
        return $this->execute('OPTIONS', $path, $query);
200
    }
201
202
    /**
203
     * Execute a custom request
204
     *
205
     * @param string $method The request method
206
     * @param string $path Path relative to the API URL
207
     * @param array $query Query parameters to include in the URL (optional)
208
     * @param array $data Data to be sent through the HTTP headers (optional)
209
     * @return ResourceGeneric The resource obtained by the request
210
     */
211 6
    public function execute($method, $path, array $query = [], array $data = [])
212
    {
213 6
        $url = $this->getApiUrl($path, $query);
214 6
        $request = $this->buildRequest($method, $url, $data);
215 6
        $response = $this->getParsedResponse($request);
216 6
        return $this->buildResource($response);
217
    }
218
219
    /**
220
     * Build and return an appropriate request.
221
     *
222
     * @internal
223
     * @param string $method
224
     * @param string $url
225
     * @param array $data
226
     * @return RequestInterface
227
     */
228 9
    public function buildRequest($method, $url, array $data = [])
229
    {
230 9
        $token = $this->getToken();
231 9
        $options = $this->buildOptions($data);
232
233 9
        return empty($token)
234 7
            ? $this->getRequest($method, $url, $options)
235 9
            : $this->getAuthenticatedRequest($method, $url, $token, $options);
236
    }
237
238
    /**
239
     * Build and return a resource.
240
     *
241
     * @internal
242
     * @param  array $response
243
     * @return ResourceGeneric
244
     */
245 6
    public function buildResource(array $response)
246
    {
247 6
        return new ResourceGeneric($response);
248
    }
249
250
    /**
251
     * Convert data to HTTP headers.
252
     *
253
     * @internal
254
     * @param array $data
255
     * @return array
256
     */
257 9
    private function buildOptions(array $data)
258
    {
259 9
        return empty($data) ? $data : [
260 1
            'headers' => ['content-type' => 'application/json'],
261 9
            'body' => json_encode($data)
262
        ];
263
    }
264
}
265