MatiHttpClient::createVerification()   B
last analyzed

Complexity

Conditions 6
Paths 17

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 8.7857
c 0
b 0
f 0
cc 6
nc 17
nop 4
1
<?php
2
3
namespace WeDevBr\Mati;
4
5
use Illuminate\Http\Client\RequestException;
6
use Illuminate\Http\Client\Response;
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Facades\Http;
9
use LogicException;
10
use TypeError;
11
use WeDevBr\Mati\Support\Contracts\IdentityInputInterface;
12
use WeDevBr\Mati\Support\Contracts\MatiClientInterface;
13
14
/**
15
 * Mati HTTP client
16
 *
17
 * @author Gabriel Mineiro <[email protected]>
18
 */
19
class MatiHttpClient implements MatiClientInterface
20
{
21
    /**
22
     * Bearer token used in API calls
23
     *
24
     * @var string
25
     */
26
    protected $access_token;
27
28
    public function __construct(string $access_token = null)
29
    {
30
        $this->access_token = $access_token;
31
    }
32
33
    /**
34
     * Set an access token to be used by the requests
35
     *
36
     * @param string $access_token
37
     * @return self
38
     */
39
    public function withToken(string $access_token): MatiClientInterface
40
    {
41
        $this->access_token = $access_token;
42
        return $this;
43
    }
44
45
    /**
46
     * Get an access token from the OAuth service
47
     *
48
     * @param string $client_id
49
     * @param string $client_secret
50
     * @return Response
51
     * @throws RequestException
52
     */
53
    public function getAccessToken(string $client_id, string $client_secret): Response
54
    {
55
        return Http::withBasicAuth($client_id, $client_secret)
56
            ->asForm()
57
            ->post(
58
                $this->getAuthURL(),
59
                ['grant_type' => 'client_credentials', 'scope' => 'verification_flow']
60
            )
61
            ->throw();
62
    }
63
64
    /**
65
     * Create a new verification process
66
     *
67
     * @param array|null $metadata Key/Value pair of data to identify the user
68
     * @param string|null $flowId
69
     * @param string|null $user_ip
70
     * @param string|null $user_agent
71
     * @return Response
72
     * @throws RequestException|LogicException
73
     */
74
    public function createVerification(
75
        $metadata = null,
76
        $flowId = null,
77
        $user_ip = null,
78
        $user_agent = null
79
    ): Response {
80
        if (!$this->access_token) {
81
            throw new LogicException('No access token given to create identity');
82
        }
83
84
        $payload = [];
85
        $request = Http::withToken($this->access_token);
86
87
        if ($metadata) {
88
            $payload['metadata'] = $metadata;
89
        }
90
91
        if ($flowId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $flowId of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
92
            $payload['flowId'] = $flowId;
93
        }
94
95
        if ($user_ip) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user_ip of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
96
            $request->withHeaders(['X-Forwarded-For' => $user_ip]);
97
        }
98
99
        if ($user_agent) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $user_agent of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
100
            $request->withHeaders(['User-Agent' => $user_agent]);
101
        }
102
103
        return $request->post($this->getApiUrl() . '/verifications', $payload)
104
            ->throw();
105
    }
106
107
    /**
108
     * Send an input for a document, selfie or other file required during a process
109
     *
110
     * @param string $identity_id
111
     * @param IdentityInputInterface[]|Collection $inputs
112
     *
113
     * @throws LogicException|RequestException|TypeError
114
     * @return Response
115
     */
116
    public function sendInput(string $identity_id, $inputs): Response
117
    {
118
        if (!$this->access_token) {
119
            throw new LogicException('No access token given to send input');
120
        }
121
122
        $inputs_collection = null;
0 ignored issues
show
Unused Code introduced by
$inputs_collection is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
123
124
        if (is_array($inputs)) {
125
            $inputs_collection = collect($inputs);
126
        } elseif ($inputs instanceof Collection) {
127
            $inputs_collection = $inputs;
128
        } else {
129
            throw new TypeError('Inputs param must be an array or a Collection');
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with 'Inputs param must be an array or a Collection'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
130
        }
131
132
        if (
133
            !$inputs_collection->every(function ($input) {
134
                return $input instanceof IdentityInputInterface;
135
            })
136
        ) {
137
            throw new TypeError('Every item of inputs must be instance of IdentityInputInterface');
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with 'Every item of inputs mu...IdentityInputInterface'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
138
        }
139
140
        $request = Http::withToken($this->access_token)
141
            ->asMultipart();
142
143
        foreach ($inputs_collection as $input) {
144
            $request->attach('document', $input->getFileContents(), $input->getFileName());
145
        }
146
147
        return $request->post(
148
            $this->getApiUrl() . "/identities/$identity_id/send-input",
149
            ['inputs' => $inputs_collection->toJson()]
150
        )
151
            ->throw();
152
    }
153
154
    /**
155
     * Retrieve info about a verification process
156
     *
157
     * @param string $resource_url URL received by webhook
158
     *
159
     * @throws RequestException
160
     * @return Response
161
     */
162
    public function retrieveResourceDataFromUrl(string $resource_url)
163
    {
164
        return Http::withToken($this->access_token)
165
            ->get($resource_url)
166
            ->throw();
167
    }
168
169
    /**
170
     * Retrieve info about a verification process
171
     *
172
     * @param string $verification_id
173
     *
174
     * @throws RequestException
175
     * @return Response
176
     */
177
    public function retrieveResourceDataByVerificationId(string $verification_id)
178
    {
179
        return $this->retrieveResourceDataFromUrl(
180
            $this->getApiUrl() . "/verifications/$verification_id"
181
        );
182
    }
183
184
    /**
185
     * Download the file sent by the user during the verification process
186
     *
187
     * @param string $media_url
188
     *
189
     * @throws RequestException
190
     * @return Response
191
     */
192
    public function downloadVerificationMedia(string $media_url)
193
    {
194
        return Http::withToken($this->access_token)
195
            ->get($media_url)
196
            ->throw();
197
    }
198
199
    /**
200
     * Get auth API URL
201
     *
202
     * @return string
203
     */
204
    protected function getAuthUrl()
205
    {
206
        return config('mati')['auth_url'];
207
    }
208
209
    /**
210
     * Get REST API URL
211
     *
212
     * @return string
213
     */
214
    protected function getApiUrl()
215
    {
216
        return config('mati')['api_url'];
217
    }
218
}
219