Completed
Pull Request — master (#251)
by
unknown
09:26
created

OAuthClient::getClientSecret()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Yandex PHP Library
4
 *
5
 * @copyright NIX Solutions Ltd.
6
 * @link https://github.com/nixsolutions/yandex-php-library
7
 */
8
9
/**
10
 * @namespace
11
 */
12
13
namespace Yandex\OAuth;
14
15
use GuzzleHttp\Exception\ClientException;
16
use GuzzleHttp\Exception\RequestException;
17
use Yandex\Common\AbstractServiceClient;
18
use Yandex\OAuth\Exception\AuthRequestException;
19
use Yandex\OAuth\Exception\AuthResponseException;
20
21
/**
22
 * Class OAuthClient implements Yandex OAuth protocol
23
 *
24
 * @category Yandex
25
 * @package  OAuth
26
 *
27
 * @author   Eugene Zabolotniy <[email protected]>
28
 * @created  29.08.13 12:07
29
 */
30
class OAuthClient extends AbstractServiceClient
31
{
32
    /*
33
     * Authentication types constants
34
     *
35
     * The "code" type means that the application will use an intermediate code to obtain an access token.
36
     * The "token" type will result a user is redirected back to the application with an access token in a URL
37
     */
38
    const CODE_AUTH_TYPE = 'code';
39
    const TOKEN_AUTH_TYPE = 'token';
40
41
    /**
42
     * @var string
43
     */
44
    private $clientId = '';
45
46
    /**
47
     * @var string
48
     */
49
    private $clientSecret = '';
50
51
    /**
52
     * @var string
53
     */
54
    private $refreshToken = '';
55
56
    /**
57
     * @var string
58
     */
59 25
    protected $serviceDomain = 'oauth.yandex.ru';
60
61 25
    /**
62 25
     * @param string $clientId
63 25
     * @param string $clientSecret
64
     */
65
    public function __construct($clientId = '', $clientSecret = '')
66
    {
67
        $this->setClientId($clientId);
68
        $this->setClientSecret($clientSecret);
69
    }
70 25
71
    /**
72 25
     * @param string $clientId
73
     *
74 25
     * @return self
75
     */
76
    public function setClientId($clientId)
77
    {
78
        $this->clientId = $clientId;
79
80 2
        return $this;
81
    }
82 2
83
84
    /**
85
     * @param string $refreshToken
86
     *
87
     * @return self
88
     */
89
    public function setRefreshToken($refreshToken)
90 25
    {
91
        $this->refreshToken = $refreshToken;
92 25
93
        return $this;
94 25
    }
95
96
    /**
97
     * @return string
98
     */
99
    public function getClientId()
100 2
    {
101
        return $this->clientId;
102 2
    }
103
104
    /**
105
     * @return string
106
     */
107
    public function getRefreshToken()
108
    {
109
        return $this->refreshToken;
110
    }
111 2
112
    /**
113 2
     * @param string $clientSecret
114 2
     *
115 1
     * @return self
116 1
     */
117
    public function setClientSecret($clientSecret)
118 2
    {
119
        $this->clientSecret = $clientSecret;
120
121
        return $this;
122
    }
123
124
    /**
125
     * @return string
126
     */
127
    public function getClientSecret()
128
    {
129 1
        return $this->clientSecret;
130
    }
131 1
132
    /**
133 1
     * @param string $type
134
     * @param string $state optional string
0 ignored issues
show
Bug introduced by
There is no parameter named $state. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
135
     *
136
     * @return string
137
     */
138
    public function getAuthUrl($type = self::CODE_AUTH_TYPE, $addtions = null)
139
    {
140
        $url = $this->getServiceUrl('authorize') . '?response_type=' . $type . '&client_id=' . $this->clientId;
141
142
143
        if (isset($addtions)) {
144
145
            if (isset($addtions['state'])) {
146
                $url .= '&state=' . $addtions['state'];
147 6
            }
148
            
149 6
             if (isset($addtions['redirect_uri'])) {
150
                $url .= '&redirect_uri=' . $addtions['redirect_uri'];
151
            }
152 6
153 6
154 6
            if (isset($addtions['force_confirm']) && ($addtions['force_confirm'] == 'yes' || $addtions['force_confirm'] == 'no')) {
155
                $url .= '&force_confirm=' . $addtions['force_confirm'];
156
            }
157 6
158 6
159 6
            if (isset($addtions['scope']) && is_array($addtions['scope'])) {
160
                $url .= '&scope=';
161 6
162 6
                foreach ($addtions['scope'] as $item) {
163 6
                    $url .= $item . " ";
164 6
                }
165 6
            }
166 6
167 6
        }
168 6
169 2
170
        return $url;
171 2
    }
172
173 1
    /**
174
     * Sends a redirect to the Yandex authentication page.
175 1
     *
176 1
     * @param bool $exit indicates whether to stop the PHP script immediately or not
177 1
     * @param string $type a type of the authentication procedure
178 1
     * @param string $state optional string
0 ignored issues
show
Bug introduced by
There is no parameter named $state. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
179
     * @return bool|void
180
     */
181
    public function authRedirect($exit = true, $type = self::CODE_AUTH_TYPE, $addtions = null)
182 1
    {
183
        header('Location: ' . $this->getAuthUrl($type, $addtions));
184
185
        return $exit ? exit() : true;
186 4
    }
187 4
188 1
    /**
189
     * Exchanges a temporary code for an access token.
190
     *
191 3
     * @param $code
192 1
     *
193
     * @return self
194
     * @throws AuthResponseException on a response format error
195 2
     * @throws RequestException on an unknown request error
196 1
     *
197
     * @throws AuthRequestException on a known request error
198
     */
199 1 View Code Duplication
    public function requestAccessToken($code)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
200
    {
201 1
        $client = $this->getClient();
202
203 1
        try {
204 1
            $response = $client->request(
205
                'POST',
206 1
                '/token',
207
                [
208 1
                    'auth' => [
209
                        $this->clientId,
210
                        $this->clientSecret
211
                    ],
212
                    'form_params' => [
213
                        'grant_type' => 'authorization_code',
214
                        'code' => $code,
215
                        'client_id' => $this->clientId,
216
                        'client_secret' => $this->clientSecret
217
                    ]
218
                ]
219
            );
220
        } catch (ClientException $ex) {
221
            $result = $this->getDecodedBody($ex->getResponse()->getBody());
222
223
            if (is_array($result) && isset($result['error'])) {
224
                // handle a service error message
225
                $message = 'Service responsed with error code "' . $result['error'] . '".';
226
227
                if (isset($result['error_description']) && $result['error_description']) {
228
                    $message .= ' Description "' . $result['error_description'] . '".';
229
                }
230
                throw new AuthRequestException($message, 0, $ex);
231
            }
232
233
            // unknown error. not parsed error
234
            throw $ex;
235
        }
236
237
        try {
238
            $result = $this->getDecodedBody($response->getBody());
239
        } catch (\RuntimeException $ex) {
240
            throw new AuthResponseException('Server response can\'t be parsed', 0, $ex);
241
        }
242
243
        if (!is_array($result)) {
244
            throw new AuthResponseException('Server response has unknown format');
245
        }
246
247
        if (!isset($result['access_token'])) {
248
            throw new AuthResponseException('Server response doesn\'t contain access token');
249
        }
250
251
        $this->setAccessToken($result['access_token']);
252
253
        $this->setRefreshToken($result['refresh_token']);
254
255
        $lifetimeInSeconds = $result['expires_in'];
256
257
        $expireDateTime = new \DateTime();
258
        $expireDateTime->add(new \DateInterval('PT' . $lifetimeInSeconds . 'S'));
259
260
        $this->setExpiresIn($expireDateTime);
261
262
        return $this;
263
    }
264
265
266
267
268
269
270 View Code Duplication
    public function refreshAccessToken(string $refreshToken)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
271
    {
272
        $client = $this->getClient();
273
274
        try {
275
            $response = $client->request(
276
                'POST',
277
                '/token',
278
                [
279
                    'auth' => [
280
                        $this->clientId,
281
                        $this->clientSecret
282
                    ],
283
                    'form_params' => [
284
                        'refresh_token' => $refreshToken,
285
                        'grant_type' => 'refresh_token',
286
                        'client_id' => $this->clientId,
287
                        'client_secret' => $this->clientSecret
288
                    ]
289
                ]
290
            );
291
        } catch (ClientException $ex) {
292
            $result = $this->getDecodedBody($ex->getResponse()->getBody());
293
294
            if (is_array($result) && isset($result['error'])) {
295
                // handle a service error message
296
                $message = 'Service responsed with error code "' . $result['error'] . '".';
297
298
                if (isset($result['error_description']) && $result['error_description']) {
299
                    $message .= ' Description "' . $result['error_description'] . '".';
300
                }
301
                throw new AuthRequestException($message, 0, $ex);
302
            }
303
304
            // unknown error. not parsed error
305
            throw $ex;
306
        }
307
308
        try {
309
            $result = $this->getDecodedBody($response->getBody());
310
        } catch (\RuntimeException $ex) {
311
            throw new AuthResponseException('Server response can\'t be parsed', 0, $ex);
312
        }
313
314
        if (!is_array($result)) {
315
            throw new AuthResponseException('Server response has unknown format');
316
        }
317
318
        if (!isset($result['access_token'])) {
319
            throw new AuthResponseException('Server response doesn\'t contain access token');
320
        }
321
322
        $this->setAccessToken($result['access_token']);
323
324
        $this->setRefreshToken($result['refresh_token']);
325
326
        $lifetimeInSeconds = $result['expires_in'];
327
328
        $expireDateTime = new \DateTime();
329
        $expireDateTime->add(new \DateInterval('PT' . $lifetimeInSeconds . 'S'));
330
331
        $this->setExpiresIn($expireDateTime);
332
333
        return $this;
334
    }
335
336
}
337