Passed
Push — master ( d68831...58f816 )
by Bruce Pinheiro de
04:28
created

Client::request()   C

Complexity

Conditions 7
Paths 13

Size

Total Lines 38
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 21
nc 13
nop 3
dl 0
loc 38
rs 6.7272
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: brucepc
5
 * Date: 26/02/18
6
 * Time: 13:52
7
 */
8
9
namespace BPCI\SumUp\Traits;
10
11
use BPCI\SumUp\OAuth\AuthenticationHelper;
12
use BPCI\SumUp\SumUp;
13
use BPCI\SumUp\SumUpClientInterface;
14
use GuzzleHttp\Exception\BadResponseException;
15
use GuzzleHttp\Exception\ConnectException;
16
use GuzzleHttp\Exception\RequestException;
17
18
/**
19
 * Trait Client
20
 * @package BPCI\SumUp\Traits
21
 */
22
trait Client
23
{
24
    /**
25
     * @param string $action
26
     * @param mixed $object
27
     * @param string $endpoint
28
     * @return bool|null
29
     * @throws BadResponseException
30
     * @throws ConnectException
31
     */
32
    function request(string $action, $object = null, string $endpoint = null):? bool
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
33
    {
34
        /** @var SumUpClientInterface $this */
35
36
        if (!$this instanceof SumUpClientInterface) {
1 ignored issue
show
introduced by
The condition ! $this instanceof BPCI\SumUp\SumUpClientInterface can never be true.
Loading history...
37
            throw new \RuntimeException('This object doesn\'t implements the SumUpClientInterface.');
38
        }
39
40
        $scopes = $this::getScopes();
41
42
        $accessToken = AuthenticationHelper::getValidToken($this->getContext(), $this->getToken(), $scopes);
43
44
        $client = SumUp::getClient($this->getOptions());
45
        $options = AuthenticationHelper::getOAuthHeader($accessToken);
46
        if ($object !== null) {
47
            $options['form_params'] = $this::getBody($object, $action);
48
        }
49
50
        $uri = $endpoint??$this->getEndPoint();
51
52
        try {
53
            /** @var \GuzzleHttp\Psr7\Response $response */
54
            $response = $client->{$action}($uri, $options);
55
        } catch (RequestException $e) {
56
            $response = $e->getResponse();
57
        }
58
        $this->setLastResponse($response);
59
        $statusCode = $response->getStatusCode();
60
        if ($statusCode < 300 && $statusCode > 199) {
61
            $data = \GuzzleHttp\json_decode($response->getBody(), true);
62
            if ($object instanceof PropertyHandlerInterface) {
63
                $object->fillProperties($data);
64
            }
65
66
            return true;
67
        }
68
69
        return false;
70
    }
71
}
72