Connect::setManageAccountInfo()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 12
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Moip\Auth;
4
5
use JsonSerializable;
6
use Moip\Contracts\Authentication;
7
use Moip\Exceptions\InvalidArgumentException;
8
use Moip\Exceptions\UnexpectedException;
9
use Moip\Exceptions\ValidationException;
10
use Moip\Moip;
11
use Requests_Exception;
12
use Requests_Hooks;
13
use Requests_Session;
14
15
/**
16
 * Class Connect.
17
 *
18
 * For all requests involving more than one Moip Account directly, authentication through an OAuth token is required.
19
 * Using the OAuth 2.0 standard it is possible to authenticate to the Moip APIs and request the use of the APIs on behalf of another user.
20
 * In this way, another Moip user can grant you the most diverse permissions,
21
 * from receiving payments as a secondary receiver to even special actions like repayment of a payment.
22
 */
23
class Connect implements Authentication, JsonSerializable
24
{
25
    /**
26
     * @const string
27
     */
28
    const ENDPOINT_SANDBOX = 'https://connect-sandbox.moip.com.br';
29
30
    /**
31
     * @const string
32
     */
33
    const ENDPOINT_PRODUCTION = 'https://connect.moip.com.br';
34
35
    /**
36
     * @const string
37
     */
38
    const OAUTH_AUTHORIZE = '/oauth/authorize';
39
40
    /**
41
     * @const string
42
     */
43
    const OAUTH_TOKEN = '/oauth/token';
44
45
    /**
46
     * Type of request desired. Possible values: AUTHORIZATION_CODE.
47
     *
48
     * @const string
49
     */
50
    const GRANT_TYPE = 'authorization_code';
51
52
    /**
53
     * Define the type of response to be obtained. Possible values: CODE.
54
     *
55
     * @const string
56
     */
57
    const RESPONSE_TYPE = 'code';
58
59
    /**
60
     * Permission for creation and consultation of ORDERS, PAYMENTS, MULTI ORDERS, MULTI PAYMENTS, CUSTOMERS and consultation of LAUNCHES.
61
     *
62
     * @const string
63
     */
64
    const RECEIVE_FUNDS = 'RECEIVE_FUNDS';
65
66
    /**
67
     * Permission to create and consult reimbursements of ORDERS, PAYMENTS.
68
     *
69
     * @const string
70
     */
71
    const REFUND = 'REFUND';
72
73
    /**
74
     * Permission to consult ACCOUNTS registration information.
75
     *
76
     * @const string
77
     */
78
    const MANAGE_ACCOUNT_INFO = 'MANAGE_ACCOUNT_INFO';
79
80
    /**
81
     * Permission to query balance through the ACCOUNTS endpoint.
82
     *
83
     * @const string
84
     */
85
    const RETRIEVE_FINANCIAL_INFO = 'RETRIEVE_FINANCIAL_INFO';
86
87
    /**
88
     * Permission for bank transfers or for Moip accounts through the TRANSFERS endpoint.
89
     *
90
     * @const string
91
     */
92
    const TRANSFER_FUNDS = 'TRANSFER_FUNDS';
93
94
    /**
95
     * Permission to create, change, and delete notification preferences through the PREFERENCES endpoint.
96
     *
97
     * @const string
98
     */
99
    const DEFINE_PREFERENCES = 'DEFINE_PREFERENCES';
100
101
    /**
102
     * List all scopes.
103
     *
104
     * @const array
105
     */
106
    const SCOPE_ALL = [
107
        self::RECEIVE_FUNDS,
108
        self::REFUND,
109
        self::MANAGE_ACCOUNT_INFO,
110
        self::RETRIEVE_FINANCIAL_INFO,
111
        self::TRANSFER_FUNDS,
112
        self::DEFINE_PREFERENCES,
113
    ];
114
115
    /**
116
     * Unique identifier of the application that will be carried out the request.
117
     *
118
     * @var string
119
     */
120
    private $client_id;
121
122
    /**
123
     * Classic non-standard authentication and access token for integration with generic SDKs.
124
     *
125
     * @var string
126
     */
127
    private $client_secret;
128
129
    /**
130
     * Client Redirect URI.
131
     *
132
     * @var string
133
     */
134
    private $redirect_uri;
135
136
    /**
137
     * Endpoint.
138
     *
139
     * @var string
140
     */
141
    private $endpoint;
142
143
    /**
144
     * Permissions that you want (Possible values depending on the feature.).
145
     *
146
     * @var array
147
     */
148
    private $scope = [];
149
150
    /**
151
     * Validation code to retrieve the access token.
152
     *
153
     * @var string
154
     */
155
    private $code;
156
157
    /**
158
     * Connect constructor.
159
     *
160
     * @param string     $redirect_uri
161
     * @param string     $client_id
162
     * @param array|bool $scope
163
     * @param string     $endpoint
164
     */
165
    public function __construct($redirect_uri = '', $client_id = '', $scope = true, $endpoint = self::ENDPOINT_PRODUCTION)
166
    {
167
        $this->client_id = $client_id;
168
        $this->redirect_uri = $redirect_uri;
169
170
        if (is_bool($scope)) {
171
            $this->setScodeAll($scope);
172
        } else {
173
            $this->setScope($scope);
174
        }
175
176
        $this->setEndpoint($endpoint);
177
    }
178
179
    /**
180
     * Creates a new Request_Session with all the default values.
181
     * A Session is created at construction.
182
     *
183
     * @param float $timeout         How long should we wait for a response?(seconds with a millisecond precision, default: 30, example: 0.01).
184
     * @param float $connect_timeout How long should we wait while trying to connect? (seconds with a millisecond precision, default: 10, example: 0.01)
185
     *
186
     * @return \Requests_Session
187
     */
188
    public function createNewSession($timeout = 30.0, $connect_timeout = 30.0)
189
    {
190
        if (function_exists('posix_uname')) {
191
            $uname = posix_uname();
192
            $user_agent = sprintf('Mozilla/4.0 (compatible; %s; PHP/%s %s; %s; %s)',
193
                Moip::CLIENT, PHP_SAPI, PHP_VERSION, $uname['sysname'], $uname['machine']);
194
        } else {
195
            $user_agent = sprintf('Mozilla/4.0 (compatible; %s; PHP/%s %s; %s)',
196
                Moip::CLIENT, PHP_SAPI, PHP_VERSION, PHP_OS);
197
        }
198
        $sess = new Requests_Session($this->endpoint);
199
        $sess->options['timeout'] = $timeout;
200
        $sess->options['connect_timeout'] = $connect_timeout;
201
        $sess->options['useragent'] = $user_agent;
202
203
        return $sess;
204
    }
205
206
    /**
207
     * URI of oauth.
208
     *
209
     * @param $endpoint
210
     *
211
     * @return string
212
     */
213
    public function getAuthUrl($endpoint = null)
214
    {
215
        if ($endpoint !== null) {
216
            $this->endpoint = $endpoint;
217
        }
218
        $query_string = [
219
            'response_type' => self::RESPONSE_TYPE,
220
            'client_id'     => $this->client_id,
221
            'redirect_uri'  => $this->redirect_uri,
222
            'scope'         => implode(',', $this->scope),
223
        ];
224
225
        return $this->endpoint.self::OAUTH_AUTHORIZE.'?'.http_build_query($query_string);
226
    }
227
228
    /**
229
     * With the permission granted, you will receive a code that will allow you to retrieve the authentication accessToken and process requests involving another user.
230
     *
231
     * @return mixed
232
     */
233
    public function authorize()
234
    {
235
        $path = $this->endpoint.self::OAUTH_TOKEN;
236
        $headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
237
        $body = [
238
            'client_id'     => $this->client_id,
239
            'client_secret' => $this->client_secret,
240
            'grant_type'    => self::GRANT_TYPE,
241
            'code'          => $this->code,
242
            'redirect_uri'  => $this->redirect_uri,
243
        ];
244
245
        try {
246
            $http_response = $this->createNewSession()->request($path, $headers, $body, 'POST');
247
        } catch (Requests_Exception $e) {
248
            throw new UnexpectedException($e);
249
        }
250
251
        if ($http_response->status_code >= 200 && $http_response->status_code < 300) {
252
            return json_decode($http_response->body);
253
        } elseif ($http_response->status_code >= 400 && $http_response->status_code <= 499) {
254
            throw new ValidationException($http_response->status_code, $http_response->body);
0 ignored issues
show
Documentation introduced by
$http_response->body is of type string, but the function expects a array<integer,object<Moip\Exceptions\Error>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
255
        }
256
257
        throw new UnexpectedException();
258
    }
259
260
    /**
261
     * @param bool $scope
262
     *
263
     * @return $this
264
     */
265
    public function setScodeAll($scope)
266
    {
267
        if (!is_bool($scope)) {
268
            throw new InvalidArgumentException('$scope deve ser boolean, foi passado '.gettype($scope));
269
        }
270
271
        if ($scope === false) {
272
            $this->scope = [];
273
        } else {
274
            $this->scope = [];
275
            $this->setReceiveFunds(true)
276
                ->setRefund(true)
277
                ->setManageAccountInfo(true)
278
                ->setRetrieveFinancialInfo(true)
279
                ->setTransferFunds(true)
280
                ->setDefinePreferences(true);
281
        }
282
283
        return $this;
284
    }
285
286
    /**
287
     * Permission for creation and consultation of ORDERS, PAYMENTS, MULTI ORDERS, MULTI PAYMENTS, CUSTOMERS and consultation of LAUNCHES.
288
     *
289
     * @param bool $receive_funds
290
     *
291
     * @throws \Moip\Exceptions\InvalidArgumentException
292
     *
293
     * @return \Moip\Auth\Connect $this
294
     */
295 View Code Duplication
    public function setReceiveFunds($receive_funds)
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...
296
    {
297
        if (!is_bool($receive_funds)) {
298
            throw new InvalidArgumentException('$receive_funds deve ser boolean, foi passado '.gettype($receive_funds));
299
        }
300
301
        if ($receive_funds === true) {
302
            $this->setScope(self::RECEIVE_FUNDS);
303
        }
304
305
        return $this;
306
    }
307
308
    /**
309
     * Permission to create and consult reimbursements ofORDERS, PAYMENTS.
310
     *
311
     * @param bool $refund
312
     *
313
     * @throws \Moip\Exceptions\InvalidArgumentException
314
     *
315
     * @return \Moip\Auth\Connect $this
316
     */
317 View Code Duplication
    public function setRefund($refund)
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...
318
    {
319
        if (!is_bool($refund)) {
320
            throw new InvalidArgumentException('$refund deve ser boolean, foi passado '.gettype($refund));
321
        }
322
323
        if ($refund === true) {
324
            $this->setScope(self::REFUND);
325
        }
326
327
        return $this;
328
    }
329
330
    /**
331
     * Permission to consult ACCOUNTS registration information.
332
     *
333
     * @param bool $manage_account_info
334
     *
335
     * @throws \Moip\Exceptions\InvalidArgumentException
336
     *
337
     * @return \Moip\Auth\Connect $this
338
     */
339 View Code Duplication
    public function setManageAccountInfo($manage_account_info)
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...
340
    {
341
        if (!is_bool($manage_account_info)) {
342
            throw new InvalidArgumentException('$manage_account_info deve ser boolean, foi passado '.gettype($manage_account_info));
343
        }
344
345
        if ($manage_account_info === true) {
346
            $this->setScope(self::MANAGE_ACCOUNT_INFO);
347
        }
348
349
        return $this;
350
    }
351
352
    /**
353
     * Permission to query balance through the ACCOUNTS endpoint.
354
     *
355
     * @param bool $retrieve_financial_info
356
     *
357
     * @throws \Moip\Exceptions\InvalidArgumentException
358
     *
359
     * @return \Moip\Auth\Connect $this
360
     */
361 View Code Duplication
    public function setRetrieveFinancialInfo($retrieve_financial_info)
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...
362
    {
363
        if (!is_bool($retrieve_financial_info)) {
364
            throw new InvalidArgumentException('$retrieve_financial_info deve ser boolean, foi passado '.gettype($retrieve_financial_info));
365
        }
366
367
        if ($retrieve_financial_info === true) {
368
            $this->setScope(self::RETRIEVE_FINANCIAL_INFO);
369
        }
370
371
        return $this;
372
    }
373
374
    /**
375
     * Permission for bank transfers or for Moip accounts through the TRANSFERS endpoint.
376
     *
377
     * @param bool $transfer_funds
378
     *
379
     * @throws \Moip\Exceptions\InvalidArgumentException
380
     *
381
     * @return \Moip\Auth\Connect $this
382
     */
383 View Code Duplication
    public function setTransferFunds($transfer_funds)
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...
384
    {
385
        if (!is_bool($transfer_funds)) {
386
            throw new InvalidArgumentException('$transfer_funds deve ser boolean, foi passado '.gettype($transfer_funds));
387
        }
388
389
        if ($transfer_funds === true) {
390
            $this->setScope(self::TRANSFER_FUNDS);
391
        }
392
393
        return $this;
394
    }
395
396
    /**
397
     * Permission to create, change, and delete notification preferences through the PREFERENCES endpoint.
398
     *
399
     * @param bool $define_preferences
400
     *
401
     * @throws \Moip\Exceptions\InvalidArgumentException
402
     *
403
     * @return $this
404
     */
405 View Code Duplication
    public function setDefinePreferences($define_preferences)
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...
406
    {
407
        if (!is_bool($define_preferences)) {
408
            throw new InvalidArgumentException('$define_preferences deve ser boolean, foi passado '.gettype($define_preferences));
409
        }
410
411
        if ($define_preferences === true) {
412
            $this->setScope(self::DEFINE_PREFERENCES);
413
        }
414
415
        return $this;
416
    }
417
418
    /**
419
     * Unique identifier of the application that will be carried out the request.
420
     *
421
     * @return mixed
422
     */
423
    public function getClientId()
424
    {
425
        return $this->client_id;
426
    }
427
428
    /**
429
     * Unique identifier of the application that will be carried out the request.
430
     *
431
     * @param mixed $client_id
432
     *
433
     * @return \Moip\Auth\Connect
434
     */
435
    public function setClientId($client_id)
436
    {
437
        $this->client_id = $client_id;
438
439
        return $this;
440
    }
441
442
    /**
443
     * Client Redirect URI.
444
     *
445
     * @return mixed
446
     */
447
    public function getRedirectUri()
448
    {
449
        return $this->redirect_uri;
450
    }
451
452
    /**
453
     * Client Redirect URI.
454
     *
455
     * @param mixed $redirect_uri
456
     *
457
     * @return \Moip\Auth\Connect
458
     */
459
    public function setRedirectUri($redirect_uri)
460
    {
461
        $this->redirect_uri = $redirect_uri;
462
463
        return $this;
464
    }
465
466
    /**
467
     * Permissions that you want (Possible values depending on the feature.).
468
     *
469
     * @return mixed
470
     */
471
    public function getScope()
472
    {
473
        return $this->scope;
474
    }
475
476
    /**
477
     * Permissions that you want (Possible values depending on the feature.).
478
     *
479
     * @param array|string $scope
480
     *
481
     * @return \Moip\Auth\Connect
482
     */
483
    public function setScope($scope)
484
    {
485
        if (!in_array($scope, self::SCOPE_ALL, true)) {
486
            throw new InvalidArgumentException();
487
        }
488
489
        if (is_array($scope)) {
490
            $this->scope = $scope;
491
        }
492
493
        $this->scope[] = $scope;
494
495
        return $this;
496
    }
497
498
    /**
499
     * @param string $endpoint
500
     *
501
     * @return \Moip\Auth\Connect
502
     */
503
    public function setEndpoint($endpoint)
504
    {
505
        if (!in_array($endpoint, [self::ENDPOINT_SANDBOX, self::ENDPOINT_PRODUCTION])) {
506
            throw new InvalidArgumentException('Endpoint inválido.');
507
        }
508
509
        $this->endpoint = $endpoint;
510
511
        return $this;
512
    }
513
514
    /**
515
     * @param mixed $client_secret
516
     *
517
     * @return \Moip\Auth\Connect
518
     */
519
    public function setClientSecret($client_secret)
520
    {
521
        $this->client_secret = $client_secret;
522
523
        return $this;
524
    }
525
526
    /**
527
     * @return mixed
528
     */
529
    public function getClientSecret()
530
    {
531
        return $this->client_secret;
532
    }
533
534
    /**
535
     * @param string $code
536
     *
537
     * @return \Moip\Auth\Connect
538
     */
539
    public function setCode($code)
540
    {
541
        $this->code = $code;
542
543
        return $this;
544
    }
545
546
    /**
547
     * @return string
548
     */
549
    public function getCode()
550
    {
551
        return $this->code;
552
    }
553
554
    /**
555
     * Register hooks as needed.
556
     *
557
     * This method is called in {@see Requests::request} when the user has set
558
     * an instance as the 'auth' option. Use this callback to register all the
559
     * hooks you'll need.
560
     *
561
     * @see Requests_Hooks::register
562
     *
563
     * @param Requests_Hooks $hooks Hook system
564
     */
565
    public function register(Requests_Hooks &$hooks)
566
    {
567
        // TODO: Implement register() method.
568
    }
569
570
    /**
571
     * Specify data which should be serialized to JSON.
572
     *
573
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
574
     *
575
     * @return mixed data which can be serialized by <b>json_encode</b>,
576
     *               which is a value of any type other than a resource.
577
     *
578
     * @since 5.4.0
579
     */
580
    public function jsonSerialize()
581
    {
582
        // TODO: Implement jsonSerialize() method.
583
    }
584
}
585