Completed
Push — master ( ae1c3d...eb4059 )
by Sébastien
10:48
created

OAuth   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 18
c 1
b 0
f 0
dl 0
loc 70
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A token() 0 13 1
A withToken() 0 5 1
A __construct() 0 3 1
A requestToken() 0 14 1
1
<?php
2
3
namespace Sebdesign\VivaPayments;
4
5
use GuzzleHttp\RequestOptions;
6
7
class OAuth
8
{
9
    /**
10
     * @var \Sebdesign\VivaPayments\Client
11
     */
12
    protected $client;
13
14
    /**
15
     * Constructor.
16
     */
17
    public function __construct(Client $client)
18
    {
19
        $this->client = $client;
20
    }
21
22
    /**
23
     * Request access token and set it to the client.
24
     *
25
     * @param  string|null $clientId
26
     * @param  string|null $clientSecret
27
     * @param  array       $guzzleOptions
28
     * @return \stdClass
29
     */
30
    public function requestToken(
31
        ?string $clientId = null,
32
        ?string $clientSecret = null,
33
        array $guzzleOptions = []
34
    ) {
35
        $response = $this->token(
36
            $clientId ?? config('services.viva.client_id'),
37
            $clientSecret ?? config('services.viva.client_secret'),
38
            $guzzleOptions
39
        );
40
41
        $this->withToken($response->access_token);
42
43
        return $response;
44
    }
45
46
    /**
47
     * Set the given token to the client.
48
     */
49
    public function withToken(string $token): self
50
    {
51
        $this->client->withToken($token);
52
53
        return $this;
54
    }
55
56
    /**
57
     * Request access token.
58
     *
59
     * @param  string $clientId
60
     * @param  string $clientSecret
61
     * @param  array  $guzzleOptions Additional options for the Guzzle client
62
     * @return \stdClass
63
     */
64
    public function token(
65
        string $clientId,
66
        string $clientSecret,
67
        array $guzzleOptions = []
68
    ) {
69
        $parameters = ['grant_type' => 'client_credentials'];
70
71
        return $this->client->post(
72
            $this->client->getAccountsUrl()->withPath('/connect/token'),
73
            array_merge([
74
                RequestOptions::FORM_PARAMS => $parameters,
75
                RequestOptions::AUTH => [$clientId, $clientSecret],
76
            ], $guzzleOptions)
77
        );
78
    }
79
}
80